﻿using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.IT;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.Print;
using Coldairarrow.Entity.TD;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_StockUpBusiness : BaseBusiness<PB_PickUpList>, IPB_StockUpBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        readonly ICheckOperation _check;
        readonly IOperatorDept _opdept;
        public PB_StockUpBusiness(IDbAccessor db, IOperator @operator, ICheckOperation @check, IOperatorDept @opdept)
            : base(db)
        {
            _operator = @operator;
            _check = @check;
            _opdept = @opdept;
        }

        #region 外部接口

        public async Task<PageResult<PB_PickUpList>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_PickUpList>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_PickUpList, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PB_PickUpList> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(PB_PickUpList data)
        {
            await InsertAsync(data);

        }

        public async Task UpdateDataAsync(PB_PickUpList data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }
        /// <summary>
        /// 事务包裹
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task<AjaxResult> AddMaterialData(SaveStockData data)
        {
            AjaxResult falseReturn = new AjaxResult
            {
                Success = false,
                Msg = "失败请重新刷新库存！库存量不足"
            };
            #region    判断数据是否大于 
            var LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().ToListAsync();
            for (int i = 0; i < data.subMData?.Count; i++)
            {
                var LocalMaterialInfo = LocalMaterial.Where(P => P.LocalId == data.subMData[i].LocationId && P.MaterialId == data.subMData[i].MaterialId).FirstOrDefault();
                if (LocalMaterialInfo == null)
                {
                    return falseReturn;
                }
                if ((LocalMaterialInfo.Nums_N + LocalMaterialInfo.Nums_O - LocalMaterialInfo.Nums_R) < data.subMData[i].StockVolume)
                {
                    return falseReturn;
                }
            }
            #endregion
            #region 修改库存数据 变成备货中 就不可以再次备货了
            #endregion
            List<PB_PickUpList> ListDesignDetail = new List<PB_PickUpList>();
            #region 备货通知单
            PB_PickUpMain pB_WarehousingNotice = new PB_PickUpMain();
            string dataId = IdHelper.GetId();
            pB_WarehousingNotice.Id = dataId;
            pB_WarehousingNotice.QrCode = "21," + dataId;
            pB_WarehousingNotice.CreateTime = DateTime.Now;
            pB_WarehousingNotice.CreatorId = _operator.UserId;
            pB_WarehousingNotice.Deleted = false;
            pB_WarehousingNotice.Memo = data.PData.Memo;
            pB_WarehousingNotice.StyleName = data.PData.ReserveStyleName;
            pB_WarehousingNotice.DeliveryTime = data.PData.ReserveDeliveryTime;
            pB_WarehousingNotice.CusID = data.PData.CusID;
            pB_WarehousingNotice.CusName = data.PData.CusName;
            pB_WarehousingNotice.CustomerAddress = data.PData.CustomerAddress;
            pB_WarehousingNotice.Toexamine = "待审核";
            pB_WarehousingNotice.Status = 0;
            pB_WarehousingNotice.BuildingId = data.PData.BuildingId;
            pB_WarehousingNotice.ParentId = data.ShippingId;
            #region //朱柏清 2022-03-04 朱柏清 保存项目ID 楼号ID
            var q = await Db.GetIQueryable<PB_DeliveryNoticeItem>().Where(s => s.Id == data.ShippingId).FirstOrDefaultAsync();
            var p = await Db.GetIQueryable<PB_DesignList>().Where(s => s.Id == q.DesignId).FirstOrDefaultAsync();
            pB_WarehousingNotice.BuildingNum = p.BuildingNumberID;
            pB_WarehousingNotice.ProjectId = p.ProjectId;
            pB_WarehousingNotice.AssociatedDelivery = data.PData.AssociatedDelivery;
            #endregion
            //pB_WarehousingNotice.ReviewerId = "";
            //pB_WarehousingNotice.ReviewerName ="";
            //pB_WarehousingNotice.ReviewTIme = DateTime.Now;
            pB_WarehousingNotice.UpdateTime = DateTime.Now;
            await Db.InsertAsync<PB_PickUpMain>(pB_WarehousingNotice);
            var ProjectId = p.ProjectId;
            var BuilId = p.BuildingNumberID;
            //创建完备货清单 关闭关联的发货计划明细
            string sqlMain = @" update PB_DeliveryPlanDetails set `States`=3    WHERE ProjectId='" + ProjectId + "' and BuildingId='" + BuilId + "'  and  Id='" + data.PData.AssociatedDelivery + "' ";
            await ExecuteSqlAsync(sqlMain);
            #endregion
            #region 组装数据
            string Updatesql = "";
            for (int i = 0; i < data.subMData?.Count; i++)
            {
                PB_PickUpList pB_DesignDetail = new PB_PickUpList();
                pB_DesignDetail.Id = IdHelper.GetId();//详情id
                pB_DesignDetail.ParentId = dataId;//主表ID
                pB_DesignDetail.AreaId = data.subMData[i].AreaId;//货区ID
                pB_DesignDetail.RackId = data.subMData[i].RackId;//货架ID
                pB_DesignDetail.LocationId = data.subMData[i].LocationId;//货位ID
                pB_DesignDetail.StockVolume = data.subMData[i].StockVolume;// 备货单明细数量
                pB_DesignDetail.ReadyNums = 0;
                var pb_des = await Db.GetIQueryable<PB_DesignDetail>().Where(m => m.Id == data.subMData[i].PB_DesignListInfo).FirstOrDefaultAsync();
                if (pb_des != null)
                {
                    pB_DesignDetail.Remarks = pb_des.Remarks;//备注
                }
                else
                {
                    pB_DesignDetail.Remarks = data.subMData[i].Remarks;//备注
                }
                pB_DesignDetail.MaterialId = data.subMData[i].MaterialId;//物料id

                pB_DesignDetail.CreateTime = DateTime.Now;//创建时间
                pB_DesignDetail.CreatorId = _operator?.UserId; //创建人
                pB_DesignDetail.SubId = data.subMData[i].PB_DesignListInfo;
                pB_DesignDetail.ReadyNums = 0;//已备货数量 朱柏清 2022-03-08
                pB_DesignDetail.State = 0;
                pB_DesignDetail.Deleted = false;//伪删除
                if (!string.IsNullOrEmpty(data.subMData?[i].StockVolume.ToString()))
                {
                    Updatesql += "UPDATE IT_LocalMaterial SET Nums_R = IFNULL(Nums_R,0) +'" + data.subMData[i].StockVolume + "' WHERE LocalId='" + data.subMData[i].LocationId + "' AND MaterialId='" + data.subMData[i].MaterialId + "';";
                }
                ListDesignDetail.Add(pB_DesignDetail);
            }
            if (ListDesignDetail?.Count > 0)
            {
                await Db.InsertAsync(ListDesignDetail);
            }
            if (!string.IsNullOrEmpty(Updatesql))
            {
                await ExecuteSqlAsync(Updatesql);
            }
            AjaxResult res = new AjaxResult
            {
                Success = true,
                Msg = "请求成功！"
            };

            return res;
            #endregion      
        }

        [Transactional]
        public async Task<AjaxResult> UpdateMaterialData(SaveStockData data)
        {
            //获取原有的备货单明细信息
            List<PB_PickUpList> PickUpList = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == data.PData.Id).ToListAsync();
            string sqlMain = string.Empty;
            foreach (var item in PickUpList)
            {
                sqlMain += @" update  IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + item.StockVolume + " WHERE LocalId='" + item.LocationId + "' AND MaterialId='" + item.MaterialId + "'; ";
            }
            //恢复修改前的库存占用量
            await ExecuteSqlAsync(sqlMain);
            //删除修改之前的备货明细
            await ExecuteSqlAsync(" delete from PB_PickUpList where ParentId='" + data.PData.Id + "'");


            List<PB_PickUpList> ListDesignDetail = new List<PB_PickUpList>();
            #region 组装数据
            string Updatesql = "";
            for (int i = 0; i < data.subMData?.Count; i++)
            {
                PB_PickUpList pB_DesignDetail = new PB_PickUpList();
                pB_DesignDetail.Id = IdHelper.GetId();//详情id
                pB_DesignDetail.ParentId = data.PData.Id;//主表ID
                pB_DesignDetail.AreaId = data.subMData[i].AreaId;//货区ID
                pB_DesignDetail.RackId = data.subMData[i].RackId;//货架ID
                pB_DesignDetail.LocationId = data.subMData[i].LocationId;//货位ID
                pB_DesignDetail.StockVolume = data.subMData[i].StockVolume;// 备货单明细数量
                pB_DesignDetail.MaterialId = data.subMData[i].MaterialId;//物料id
                var pb_des = await Db.GetIQueryable<PB_DesignDetail>().Where(m => m.Id == data.subMData[i].PB_DesignListInfo).FirstOrDefaultAsync();
                if (pb_des != null)
                {
                    pB_DesignDetail.Remarks = pb_des.Remarks;//备注
                }
                else
                {
                    pB_DesignDetail.Remarks = data.subMData[i].Remarks;//备注
                }
                pB_DesignDetail.CreateTime = DateTime.Now;//创建时间
                pB_DesignDetail.CreatorId = _operator?.UserId; //创建人
                pB_DesignDetail.SubId = data.subMData[i].PB_DesignListInfo;
                pB_DesignDetail.ReadyNums = 0;//已备货数量 朱柏清 2022-03-08
                pB_DesignDetail.State = 0;
                pB_DesignDetail.Deleted = false;//伪删除
                if (!string.IsNullOrEmpty(data.subMData?[i].StockVolume.ToString()))
                {
                    Updatesql += @"UPDATE IT_LocalMaterial SET Nums_R = IFNULL(Nums_R,0) +'" + data.subMData[i].StockVolume + "' WHERE LocalId='" + data.subMData[i].LocationId + "' AND MaterialId='" + data.subMData[i].MaterialId + "'; ";
                }
                ListDesignDetail.Add(pB_DesignDetail);
            }
            #endregion


            if (ListDesignDetail.Count > 0)
            {
                await Db.InsertAsync<PB_PickUpList>(ListDesignDetail);

            }
            if (Updatesql.Length > 0)
            {
                await ExecuteSqlAsync(Updatesql);
            }
            await ExecuteSqlAsync(" UPDATE  PB_PickUpMain set UpdateTime=NOW()  where Id='" + data.PData.Id + "'");
            AjaxResult res = new AjaxResult
            {
                Success = true,
                Msg = "请求成功！"
            };

            return res;
        }

        /// <summary>
        /// 获取备货单对应的包明细
        /// </summary>
        /// <param name="stockupQrCode">备货单二维码</param>
        /// <returns></returns>
        public async Task<List<PB_UnLoadListDataDTO>> GetStockUpDetailListDataAsync(string stockupQrCode)
        {
            string stockupid = stockupQrCode.Split(',')?[1].ToString();
            //string sqlMain = @" select * from ( select b.PackId,b.MaterialId,c.BoxNo,c.BoxName,(concat(e.`Name`,'/',f.`Name`,'/',d.`Name`)) as LocalName,g.Spec as MaterialSpec,b.Nums as StockNumber,b.CreateTime,c.QrCode from PB_PickUpList as a join PB_UnLoadList as b on a.Id=b.ParentId join PB_PackList as c on b.PackId=c.Id join PB_Location as d on b.LocalId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id left join PB_Material as g on b.MaterialId=g.Id where a.ParentId='" + stockupid + "' and  c.PackageType=0     UNION ALL 	 select PackId,'' as MaterialId,BoxNo,BoxName,LocalName,'' as MaterialSpec,SUM(StockNumber) as StockNumber,CreateTime,QrCode from (	select b.PackId,b.MaterialId,c.BoxNo,c.BoxName,(concat(e.`Name`,'/',f.`Name`,'/',d.`Name`)) as LocalName,g.Spec as MaterialSpec,b.Nums as StockNumber,DATE_FORMAT(b.CreateTime,'%Y-%m-%d') as CreateTime,c.QrCode from PB_PickUpList as a join PB_UnLoadList as b on a.Id=b.ParentId join PB_PackList as c on b.PackId=c.Id join PB_Location as d on b.LocalId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id left join PB_Material as g on b.MaterialId=g.Id where a.ParentId='" + stockupid + "' and  c.PackageType=1 )as t group by PackId,BoxNo,BoxName,LocalName,CreateTime,QrCode     UNION all 	select b.PackId,b.MaterialId,c.Id as BoxNo,c.Name as BoxName,(concat(e.`Name`,'/',f.`Name`,'/',d.`Name`)) as LocalName,c.Spec as MaterialSpec,b.Nums as StockNumber,b.CreateTime,concat('04,',b.MaterialId) as QrCode from PB_PickUpList as a join PB_UnLoadList as b on a.Id=b.ParentId join PB_Material as c on b.MaterialId=c.Id join PB_Location as d on b.LocalId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id where a.ParentId='" + stockupid + "' and b.PackId='' ) as t order by CreateTime desc ";
            PB_PickUpMain pB_PickUpMain = await Db.GetIQueryable<PB_PickUpMain>().Where(x => x.Id == stockupid).FirstOrDefaultAsync();
            string sqlMain = "";
            if (pB_PickUpMain.Status < 3)
            {
                List<TD_OutStorage> tD_OutStorages = await Db.GetIQueryable<TD_OutStorage>().Where(x => x.RefCode == stockupid).ToListAsync();
                int outstoragesnum = tD_OutStorages.Count + 1;

                string sql = @"select * from (
 select b.PackId,b.MaterialId,b.JobId,c.BoxNo,c.BoxName,(concat(e.`Name`,'/',f.`Name`,'/',d.`Name`)) as LocalName,g.Spec as MaterialSpec,b.Nums as StockNumber,b.CreateTime,c.QrCode from PB_PickUpList as a join PB_UnLoadList as b on a.Id=b.ParentId  and b.OutNum={1} join PB_PackList as c on b.PackId=c.Id join PB_Location as d on b.LocalId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id left join PB_Material as g on b.MaterialId=g.Id where a.ParentId='{0}' and  c.PackageType=0     
  UNION ALL 	 
  select PackId,'' as MaterialId,'' as JobId,BoxNo,BoxName,LocalName,'' as MaterialSpec,SUM(StockNumber) as StockNumber,CreateTime,QrCode from (	
 select b.PackId,b.MaterialId,c.BoxNo,c.BoxName,(concat(e.`Name`,'/',f.`Name`,'/',d.`Name`)) as LocalName,g.Spec as MaterialSpec,b.Nums as StockNumber,DATE_FORMAT(b.CreateTime,'%Y-%m-%d') as CreateTime,c.QrCode from PB_PickUpList as a join PB_UnLoadList as b on a.Id=b.ParentId and b.OutNum={1} join PB_PackList as c on b.PackId=c.Id join PB_Location as d on b.LocalId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id left join PB_Material as g on b.MaterialId=g.Id where a.ParentId='{0}' and  c.PackageType=1 
 )as t group by PackId,BoxNo,BoxName,LocalName,CreateTime,QrCode     
  UNION all 	
  select b.PackId,b.MaterialId,b.JobId,c.Id as BoxNo,c.Name as BoxName,(concat(e.`Name`,'/',f.`Name`,'/',d.`Name`)) as LocalName,c.Spec as MaterialSpec,b.Nums as StockNumber,b.CreateTime,concat('04,',b.MaterialId) as QrCode from PB_PickUpList as a join PB_UnLoadList as b on a.Id=b.ParentId and b.OutNum={1} join PB_Material as c on b.MaterialId=c.Id join PB_Location as d on b.LocalId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id where a.ParentId='{0}' and b.PackId='' and b.JobId=''
  UNION all 	
  select b.PackId,b.MaterialId,b.JobId,c.Id as BoxNo,c.Name as BoxName,(concat(e.`Name`,'/',f.`Name`,'/',d.`Name`)) as LocalName,c.Spec as MaterialSpec,b.Nums as StockNumber,b.CreateTime,concat('14,',b.JobId) as QrCode from PB_PickUpList as a join PB_UnLoadList as b on a.Id=b.ParentId and b.OutNum={1} join PB_Material as c on b.MaterialId=c.Id join PB_Location as d on b.LocalId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id where a.ParentId='{0}' and b.PackId='' and b.JobId!=''
) as t order by CreateTime desc ";
                sqlMain = string.Format(sql, stockupid, outstoragesnum);
            }
            else if (pB_PickUpMain.Status == 3)
            {
                string sql = @"select * from (
 select b.PackId,b.MaterialId,b.JobId,c.BoxNo,c.BoxName,(concat(e.`Name`,'/',f.`Name`,'/',d.`Name`)) as LocalName,g.Spec as MaterialSpec,b.Nums as StockNumber,b.CreateTime,c.QrCode from PB_PickUpList as a join PB_UnLoadList as b on a.Id=b.ParentId  join PB_PackList as c on b.PackId=c.Id join PB_Location as d on b.LocalId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id left join PB_Material as g on b.MaterialId=g.Id where a.ParentId='{0}' and  c.PackageType=0     
  UNION ALL 	 
  select PackId,'' as MaterialId,'' as JobId,BoxNo,BoxName,LocalName,'' as MaterialSpec,SUM(StockNumber) as StockNumber,CreateTime,QrCode from (	
 select b.PackId,b.MaterialId,c.BoxNo,c.BoxName,(concat(e.`Name`,'/',f.`Name`,'/',d.`Name`)) as LocalName,g.Spec as MaterialSpec,b.Nums as StockNumber,DATE_FORMAT(b.CreateTime,'%Y-%m-%d') as CreateTime,c.QrCode from PB_PickUpList as a join PB_UnLoadList as b on a.Id=b.ParentId join PB_PackList as c on b.PackId=c.Id join PB_Location as d on b.LocalId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id left join PB_Material as g on b.MaterialId=g.Id where a.ParentId='{0}' and  c.PackageType=1 
 )as t group by PackId,BoxNo,BoxName,LocalName,CreateTime,QrCode     
  UNION all 	
  select b.PackId,b.MaterialId,b.JobId,c.Id as BoxNo,c.Name as BoxName,(concat(e.`Name`,'/',f.`Name`,'/',d.`Name`)) as LocalName,c.Spec as MaterialSpec,b.Nums as StockNumber,b.CreateTime,concat('04,',b.MaterialId) as QrCode from PB_PickUpList as a join PB_UnLoadList as b on a.Id=b.ParentId join PB_Material as c on b.MaterialId=c.Id join PB_Location as d on b.LocalId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id where a.ParentId='{0}' and b.PackId='' and b.JobId=''
  UNION all 	
  select b.PackId,b.MaterialId,b.JobId,c.Id as BoxNo,c.Name as BoxName,(concat(e.`Name`,'/',f.`Name`,'/',d.`Name`)) as LocalName,c.Spec as MaterialSpec,b.Nums as StockNumber,b.CreateTime,concat('14,',b.JobId) as QrCode from PB_PickUpList as a join PB_UnLoadList as b on a.Id=b.ParentId join PB_Material as c on b.MaterialId=c.Id join PB_Location as d on b.LocalId=d.Id join PB_StorArea as e on d.AreaId=e.Id join PB_Rack as f on d.RackId=f.Id where a.ParentId='{0}' and b.PackId='' and b.JobId!=''
) as t order by CreateTime desc ";
                sqlMain = string.Format(sql, stockupid);
            }
            return await Db.GetListBySqlAsync<PB_UnLoadListDataDTO>(sqlMain);
        }

        /// <summary>
        /// 删除备货单已出库的明细
        /// </summary>
        /// <param name="stockupQrCode">备货单二维码</param>
        /// <param name="packqrocde">包二维码</param>
        /// <param name="Nums">包二维码</param>
        /// <returns></returns>
        [Transactional]
        public async Task DeleteStockUpDetailListDataAsync(string stockupQrCode, string packqrocde, double Nums)
        {
            Base_User basedata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            string stockupid = stockupQrCode.Split(',')?[1].ToString();   //备货单id
            string packid = string.Empty;
            string materialId = string.Empty;
            string jobid = string.Empty;
            string packmodel = packqrocde.Split(',')?[0].ToString();
            if (packmodel == "13")
            {
                packid = packqrocde.Split(',')?[1].ToString();
            }
            else if (packmodel == "04")
            {
                var model = packqrocde.Split(',');
                if (model.Length > 2)
                {
                    materialId = model?[3].ToString();
                }
                else
                {
                    materialId = model?[1].ToString();
                }
            }
            else if (packmodel == "14")
            {
                jobid = packqrocde.Split(',')?[1].ToString();
            }
            string sqlMain = string.Empty;
            List<PB_Stock> StockList = new List<PB_Stock>();
            List<PB_StockLog> StockLogList = new List<PB_StockLog>();
            List<IT_LocalDetail> LocalDetailList = new List<IT_LocalDetail>();

            if (packmodel == "13")
            {
                PB_PackList pbdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packid).FirstOrDefaultAsync();
                if (pbdata.PackageType == 0)
                {
                    Expression<Func<PB_UnLoadList, PB_Location, PB_Material, PB_UnLoadListDataListDTO>> packselect = (a, b, c) => new PB_UnLoadListDataListDTO
                    {
                        LocationId = b.Id,
                        StorId = b.StorId,
                        AreaId = b.AreaId,
                        RackId = b.RackId,
                        MeasureId = c.storageId
                    };
                    packselect = packselect.BuildExtendSelectExpre();
                    var packdata = from a in Db.GetIQueryable<PB_UnLoadList>().AsExpandable()
                                   join b in Db.GetIQueryable<PB_Location>() on a.LocalId equals b.Id into ab
                                   from b in ab.DefaultIfEmpty()
                                   join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                                   from c in ac.DefaultIfEmpty()
                                   select @packselect.Invoke(a, b, c);
                    var unloaddata = await packdata.Where(x => x.PackId == packid).FirstOrDefaultAsync();
                    if (unloaddata == null)
                    {
                        throw new BusException("已移除不能重复移除");
                    }
                    //删除备货出库的明细
                    sqlMain += @" delete from PB_UnLoadList where PackId='" + packid + "'; ";
                    //修改包的状态为入库
                    sqlMain += @" update PB_PackList set Status=3,OutStorTime=NULL,OutStorUserId=NULL,OutStorUserName=NULL where Id='" + packid + "'; ";
                    //减去备货单明细的出库数量
                    sqlMain += @" update PB_PickUpList set ReadyNums=IFNULL(ReadyNums,0)-" + pbdata.Nums + " where Id='" + unloaddata.ParentId + "' and MaterialId='" + pbdata.MaterialId + "'; ";
                    //await ExecuteSqlAsync(sqlMain);
                    var pb_PickListSteps = Db.GetIQueryable<PB_PickListSteps>().Where(x => x.ParentId == stockupid && x.MaterialId == pbdata.MaterialId && x.ReadyNums > 0).ToList();

                    if (pb_PickListSteps.Count > 0)
                    {
                        bool Isfal = false;
                        double? nums = pbdata.Nums;
                        //string sqlupdate = "";
                        for (int i = pb_PickListSteps.Count - 1; i >= 0; i--)
                        {
                            var pb = await Db.GetIQueryable<PB_PickListSteps>().Where(m => m.Id == pb_PickListSteps[i].Id).FirstOrDefaultAsync();
                            nums = nums - pb.ReadyNums;
                            if (Isfal == false)
                            {
                                if (nums < 0)
                                {
                                    double? values = pb.ReadyNums - (nums + pb.ReadyNums);

                                    sqlMain += @"update  PB_PickListSteps set ReadyNums=" + values + " where Id='" + pb_PickListSteps[i].Id + "';";
                                    Isfal = true;
                                }
                                else
                                {
                                    sqlMain += @"update  PB_PickListSteps set ReadyNums=0 where Id='" + pb_PickListSteps[i].Id + "';";

                                }
                            }
                        }
                    }

                    PB_Stock stockdata = new PB_Stock();
                    stockdata.Id = IdHelper.GetId();
                    stockdata.PackId = packid;
                    stockdata.StorId = unloaddata.StorId;
                    stockdata.LocationId = unloaddata.LocationId;
                    stockdata.StockNumber = pbdata.Nums;
                    stockdata.MaterialId = pbdata.MaterialId;
                    stockdata.CreatorId = _operator.UserId;
                    stockdata.CreatorName = basedata.RealName;
                    stockdata.CreateTime = DateTime.Now;
                    stockdata.OperatorId = _operator.UserId;
                    stockdata.Type = 1;
                    stockdata.OrderID = stockupid;
                    stockdata.OldOrNew = pbdata.OldOrNew;
                    stockdata.AreaId = unloaddata.AreaId;
                    stockdata.RackId = unloaddata.RackId;
                    stockdata.JobId = "";
                    StockList.Add(stockdata);

                    PB_StockLog stockdatalog = new PB_StockLog();
                    stockdatalog.Id = IdHelper.GetId();
                    stockdatalog.PackId = packid;
                    stockdatalog.StorId = unloaddata.StorId;
                    stockdatalog.LocationId = unloaddata.LocationId;
                    stockdatalog.StockNumber = pbdata.Nums;
                    stockdatalog.MaterialId = pbdata.MaterialId;
                    stockdatalog.CreatorId = _operator.UserId;
                    stockdatalog.CreatorName = basedata.RealName;
                    stockdatalog.CreateTime = DateTime.Now;
                    stockdatalog.OperatorId = _operator.UserId;
                    stockdatalog.Type = 1;
                    stockdatalog.OrderID = stockupid;
                    stockdatalog.OldOrNew = pbdata.OldOrNew;
                    stockdatalog.State = 0;
                    stockdatalog.JobId = "";
                    StockLogList.Add(stockdatalog);

                    IT_LocalDetail itdata = new IT_LocalDetail();
                    itdata.Id = IdHelper.GetId();
                    itdata.StorId = unloaddata.StorId;
                    itdata.LocalId = unloaddata.LocationId;
                    itdata.MaterialId = pbdata.MaterialId;
                    itdata.MeasureId = unloaddata.MeasureId;
                    itdata.BarCode = pbdata.QrCode;
                    itdata.InTime = DateTime.Now;
                    itdata.CreateTime = DateTime.Now;
                    itdata.CreatorId = _operator.UserId;
                    itdata.Deleted = false;
                    itdata.Num = pbdata.Nums;
                    itdata.PackId = packid;
                    itdata.OldOrNew = pbdata.OldOrNew;
                    itdata.JobId = "";
                    LocalDetailList.Add(itdata);

                    PB_PickUpList PickUpList = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupid && x.MaterialId == unloaddata.MaterialId).FirstOrDefaultAsync();

                    if (pbdata.OldOrNew == 0)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + pbdata.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + pbdata.Nums + " where MaterialId='" + pbdata.MaterialId + "' and StorId='" + unloaddata.StorId + "' and LocalId='" + unloaddata.LocationId + "'; ";
                    }
                    else if (pbdata.OldOrNew == 1)
                    {
                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + pbdata.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + pbdata.Nums + " where MaterialId='" + pbdata.MaterialId + "' and StorId='" + unloaddata.StorId + "' and LocalId='" + unloaddata.LocationId + "'; ";
                    }

                    //恢复备货单的占用量
                    sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)+" + pbdata.Nums + " where MaterialId='" + pbdata.MaterialId + "' and LocalId='" + PickUpList.LocationId + "'; ";
                }
                else if (pbdata.PackageType == 1)
                {
                    Expression<Func<PB_UnLoadList, PB_Location, PB_Material, PB_UnLoadListDataListDTO>> packselect = (a, b, c) => new PB_UnLoadListDataListDTO
                    {
                        LocationId = b.Id,
                        StorId = b.StorId,
                        AreaId = b.AreaId,
                        RackId = b.RackId,
                        MeasureId = c.storageId
                    };
                    packselect = packselect.BuildExtendSelectExpre();
                    var packdata = from a in Db.GetIQueryable<PB_UnLoadList>().AsExpandable()
                                   join b in Db.GetIQueryable<PB_Location>() on a.LocalId equals b.Id into ab
                                   from b in ab.DefaultIfEmpty()
                                   join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                                   from c in ac.DefaultIfEmpty()
                                   select @packselect.Invoke(a, b, c);
                    var unloaddata = await packdata.Where(x => x.PackId == packid).ToListAsync();

                    if (unloaddata == null)
                    {
                        throw new BusException("已移除不能重复移除");
                    }

                    //删除备货出库的明细
                    sqlMain += @" delete from PB_UnLoadList where PackId='" + packid + "'; ";
                    //修改包的状态为入库
                    sqlMain += @" update PB_PackList set Status=3,OutStorTime=NULL,OutStorUserId=NULL,OutStorUserName=NULL where Id='" + packid + "'; ";
                    //await ExecuteSqlAsync(sqlMain);

                    string strStorId = string.Empty;
                    string strLocalId = string.Empty;
                    string strAreaId = string.Empty;
                    string strRackId = string.Empty;

                    foreach (var item in unloaddata)
                    {
                        PB_PickUpList PickUpList = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupid && x.MaterialId == item.MaterialId).FirstOrDefaultAsync();

                        strStorId = item.StorId;
                        strLocalId = item.LocalId;
                        strAreaId = item.AreaId;
                        strRackId = item.RackId;
                        IT_LocalDetail itdata = new IT_LocalDetail();
                        itdata.Id = IdHelper.GetId();
                        itdata.StorId = item.StorId;
                        itdata.LocalId = item.LocalId;
                        itdata.MaterialId = item.MaterialId;
                        itdata.MeasureId = item.MeasureId;
                        itdata.BarCode = pbdata.QrCode;
                        itdata.InTime = DateTime.Now;
                        itdata.CreateTime = DateTime.Now;
                        itdata.CreatorId = _operator.UserId;
                        itdata.Deleted = false;
                        itdata.Num = item.Nums;
                        itdata.PackId = packid;
                        itdata.OldOrNew = pbdata.OldOrNew;
                        itdata.JobId = "";
                        LocalDetailList.Add(itdata);

                        //减去备货单明细的出库数量
                        sqlMain += @" update PB_PickUpList set ReadyNums=IFNULL(ReadyNums,0)-" + item.Nums + " where Id='" + item.ParentId + "' and MaterialId='" + item.MaterialId + "'; ";

                        if (pbdata.OldOrNew == 0)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + item.Nums + " where MaterialId='" + item.MaterialId + "' and StorId='" + item.StorId + "' and LocalId='" + item.LocationId + "'; ";
                        }
                        else if (pbdata.OldOrNew == 1)
                        {
                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + item.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + item.Nums + " where MaterialId='" + item.MaterialId + "' and StorId='" + item.StorId + "' and LocalId='" + item.LocationId + "'; ";
                        }
                        //恢复备货单的占用量
                        sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)+" + pbdata.Nums + " where MaterialId='" + item.MaterialId + "' and LocalId='" + PickUpList.LocationId + "'; ";
                    }

                    //添加PB_Stock
                    PB_Stock stockdata = new PB_Stock();
                    stockdata.Id = IdHelper.GetId();
                    stockdata.PackId = packid;
                    stockdata.StorId = strStorId;
                    stockdata.LocationId = strLocalId;
                    stockdata.StockNumber = pbdata.Nums;
                    stockdata.MaterialId = pbdata.MaterialId;
                    stockdata.CreatorId = _operator.UserId;
                    stockdata.CreatorName = basedata.RealName;
                    stockdata.CreateTime = DateTime.Now;
                    stockdata.OperatorId = _operator.UserId;
                    stockdata.Type = 1;
                    stockdata.OrderID = stockupid;
                    stockdata.OldOrNew = pbdata.OldOrNew;
                    stockdata.AreaId = strAreaId;
                    stockdata.RackId = strRackId;
                    stockdata.JobId = "";
                    StockList.Add(stockdata);

                    //添加PB_StockLog
                    PB_StockLog stockdatalog = new PB_StockLog();
                    stockdatalog.Id = IdHelper.GetId();
                    stockdatalog.PackId = packid;
                    stockdatalog.StorId = strStorId;
                    stockdatalog.LocationId = strLocalId;
                    stockdatalog.StockNumber = pbdata.Nums;
                    stockdatalog.MaterialId = pbdata.MaterialId;
                    stockdatalog.CreatorId = _operator.UserId;
                    stockdatalog.CreatorName = basedata.RealName;
                    stockdatalog.CreateTime = DateTime.Now;
                    stockdatalog.OperatorId = _operator.UserId;
                    stockdatalog.Type = 1;
                    stockdatalog.OrderID = stockupid;
                    stockdatalog.OldOrNew = pbdata.OldOrNew;
                    stockdatalog.State = 0;
                    stockdatalog.JobId = "";
                    StockLogList.Add(stockdatalog);

                }
            }
            else if (packmodel == "04")
            {
                List<TD_OutStorage> tD_OutStorages = await Db.GetIQueryable<TD_OutStorage>().Where(x => x.RefCode == stockupid).ToListAsync();
                int outstoragesnum = tD_OutStorages.Count + 1;

                Expression<Func<PB_UnLoadList, PB_Location, PB_PickUpList, PB_Material, PB_UnLoadListDataListDTO>> packselect = (a, b, c, d) => new PB_UnLoadListDataListDTO
                {
                    LocationId = b.Id,
                    StorId = b.StorId,
                    AreaId = b.AreaId,
                    RackId = b.RackId,
                    PickListMainId = c.ParentId,
                    PickListId = c.Id,
                    MeasureId = d.storageId,
                };
                packselect = packselect.BuildExtendSelectExpre();
                var packdata = from a in Db.GetIQueryable<PB_UnLoadList>().AsExpandable()
                               join b in Db.GetIQueryable<PB_Location>() on a.LocalId equals b.Id into ab
                               from b in ab.DefaultIfEmpty()
                               join c in Db.GetIQueryable<PB_PickUpList>() on a.ParentId equals c.Id into ac
                               from c in ac.DefaultIfEmpty()
                               join d in Db.GetIQueryable<PB_Material>() on a.MaterialId equals d.Id into ad
                               from d in ad.DefaultIfEmpty()
                               select @packselect.Invoke(a, b, c, d);
                var unloaddata = await packdata.Where(x => x.PickListMainId == stockupid && x.MaterialId == materialId && x.Nums == Nums).FirstOrDefaultAsync();
                if (unloaddata == null)
                {
                    throw new BusException("已移除不能重复移除");
                }

                //删除备货出库的明细
                sqlMain += @" delete from PB_UnLoadList where MaterialId='" + unloaddata.MaterialId + "' and ParentId='" + unloaddata.PickListId + "' and Nums='" + Nums + "' and OutNum='" + outstoragesnum + "'  LIMIT 1; ";
                //减去备货单明细的出库数量
                sqlMain += @" update PB_PickUpList set ReadyNums=IFNULL(ReadyNums,0)-" + Nums + " where Id='" + unloaddata.ParentId + "' and MaterialId='" + unloaddata.MaterialId + "' ; ";

                var pb_PickListSteps = Db.GetIQueryable<PB_PickListSteps>().Where(x => x.ParentId == stockupid && x.MaterialId == unloaddata.MaterialId && x.ReadyNums != null && x.ReadyNums > 0).ToList();
                //await ExecuteSqlAsync(sqlMain);
                if (pb_PickListSteps.Count > 0)
                {
                    bool Isfal = false;
                    double? nums = Nums;
                    for (int i = pb_PickListSteps.Count - 1; i >= 0; i--)
                    {
                        var pb = await Db.GetIQueryable<PB_PickListSteps>().Where(m => m.Id == pb_PickListSteps[i].Id).FirstOrDefaultAsync();
                        nums = nums - pb.ReadyNums;
                        if (Isfal == false)
                        {
                            if (nums < 0)
                            {
                                double? values = pb.ReadyNums - (nums + pb.ReadyNums);

                                sqlMain += "update  PB_PickListSteps set ReadyNums=" + values + " where Id='" + pb_PickListSteps[i].Id + "';";

                                Isfal = true;
                            }
                            else
                            {
                                sqlMain += "update  PB_PickListSteps set ReadyNums=0 where Id='" + pb_PickListSteps[i].Id + "';";

                            }
                        }

                    }
                }
                PB_Stock stockdata = new PB_Stock();
                stockdata.Id = IdHelper.GetId();
                stockdata.PackId = packid;
                stockdata.StorId = unloaddata.StorId;
                stockdata.LocationId = unloaddata.LocationId;
                stockdata.StockNumber = Nums;
                stockdata.MaterialId = unloaddata.MaterialId;
                stockdata.CreatorId = _operator.UserId;
                stockdata.CreatorName = basedata.RealName;
                stockdata.CreateTime = DateTime.Now;
                stockdata.OperatorId = _operator.UserId;
                stockdata.Type = 1;
                stockdata.OrderID = stockupid;
                stockdata.OldOrNew = 1;
                stockdata.AreaId = unloaddata.AreaId;
                stockdata.RackId = unloaddata.RackId;
                stockdata.JobId = "";
                StockList.Add(stockdata);

                PB_StockLog stockdatalog = new PB_StockLog();
                stockdatalog.Id = IdHelper.GetId();
                stockdatalog.PackId = packid;
                stockdatalog.StorId = unloaddata.StorId;
                stockdatalog.LocationId = unloaddata.LocationId;
                stockdatalog.StockNumber = Nums;
                stockdatalog.MaterialId = unloaddata.MaterialId;
                stockdatalog.CreatorId = _operator.UserId;
                stockdatalog.CreatorName = basedata.RealName;
                stockdatalog.CreateTime = DateTime.Now;
                stockdatalog.OperatorId = _operator.UserId;
                stockdatalog.Type = 1;
                stockdatalog.OrderID = stockupid;
                stockdatalog.OldOrNew = 1;
                stockdatalog.State = 0;
                stockdatalog.JobId = "";
                StockLogList.Add(stockdatalog);

                IT_LocalDetail itdata = new IT_LocalDetail();
                itdata.Id = IdHelper.GetId();
                itdata.StorId = unloaddata.StorId;
                itdata.LocalId = unloaddata.LocationId;
                itdata.MaterialId = unloaddata.MaterialId;
                itdata.MeasureId = unloaddata.MeasureId;
                itdata.BarCode = packqrocde;
                itdata.InTime = DateTime.Now;
                itdata.CreateTime = DateTime.Now;
                itdata.CreatorId = _operator.UserId;
                itdata.Deleted = false;
                itdata.Num = Nums;
                itdata.PackId = packid;
                itdata.OldOrNew = 1;
                itdata.JobId = "";
                LocalDetailList.Add(itdata);

                sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + Nums + ",ScanNum=IFNULL(ScanNum,0)+" + Nums + " where MaterialId='" + unloaddata.MaterialId + "' and StorId='" + unloaddata.StorId + "' and LocalId='" + unloaddata.LocationId + "'; ";
                PB_PickUpList PickUpList = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.Id == unloaddata.ParentId && x.ParentId == stockupid && x.MaterialId == materialId).FirstOrDefaultAsync();
                sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)+" + Nums + " where MaterialId='" + materialId + "' and LocalId='" + PickUpList.LocationId + "'; ";


            }
            else if (packmodel == "14")
            {
                ////获取成品码的拆包记录
                //Expression<Func<PB_UnpackingDetail, PB_Unpacking, UnpackingDetailDTO>> packselect = (a, b) => new UnpackingDetailDTO
                //{
                //    PackId = b.PrimaryPackId
                //};
                //packselect = packselect.BuildExtendSelectExpre();
                //var packdata = from a in Db.GetIQueryable<PB_UnpackingDetail>().AsExpandable()
                //               join b in Db.GetIQueryable<PB_Unpacking>() on a.ParentId equals b.Id into ab
                //               from b in ab.DefaultIfEmpty()
                //               select @packselect.Invoke(a, b);
                //var unpackdata = await packdata.Where(x => x.JobBookingId == jobid && x.PickMainId == stockupid).FirstOrDefaultAsync();
                ////移除成品查询有拆包记录
                //if (unpackdata != null)
                //{
                //    //获取成品对应的备货单明细信息
                //    PB_PickUpList picklist = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.Id == unpackdata.PickListId).FirstOrDefaultAsync();

                //    PB_Location locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == picklist.LocationId).FirstOrDefaultAsync();

                //    //把成品退回到拆的包里
                //    PB_PackListInfo packinfo = new PB_PackListInfo();
                //    packinfo.Id = IdHelper.GetId();
                //    packinfo.PackId = unpackdata.PackId;
                //    packinfo.JobBookingId = jobid;
                //    packinfo.CreatorId = _operator.UserId;
                //    packinfo.CreatorTime = DateTime.Now;
                //    packinfo.CreatorName = basedata.RealName;
                //    packinfo.Deleted = false;
                //    packinfo.OldOrNew = unpackdata.OldOrNew;
                //    await Db.InsertAsync<PB_PackListInfo>(packinfo);

                //    string sqlMain = string.Empty;
                //    //把成品表成品对应的包关系恢复
                //    sqlMain += @" update PB_JobBookingQrCode set PackId='" + unpackdata.PackId + "' where Id='" + jobid + "'; ";

                //    //恢复库存汇总数量
                //    if (unpackdata.OldOrNew == 0)
                //    {
                //        sqlMain += @"update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+1,ScanNum=IFNULL(ScanNum,0)+1 where LocalId='" + picklist.LocationId + "' and MaterialId='" + picklist.MaterialId + "'; ";
                //    }
                //    else if (unpackdata.OldOrNew == 1)
                //    {
                //        sqlMain += @"update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+1,ScanNum=IFNULL(ScanNum,0)+1 where LocalId='" + picklist.LocationId + "' and MaterialId='" + picklist.MaterialId + "'; ";
                //    }
                //    //恢复物料的审核前数量
                //    sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)+1 where Id='" + picklist.MaterialId + "'; ";
                //    //恢复库存明细原包的包装数量
                //    sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)+1 where PackId='" + unpackdata.PackId + "' and MaterialId='" + picklist.MaterialId + "'; ";
                //    //恢复包的包装数量
                //    sqlMain += @" update PB_PackList set Nums=IFNULL(Nums,0)+1 where Id='" + unpackdata.PackId + "'; ";
                //    //修改备货单明细已备货数量
                //    sqlMain += @" update PB_PickUpList set ReadyNums=IFNULL(ReadyNums,0)-1 where Id='" + unpackdata.PickListId + "'; ";
                //    //恢复PB_Stock表包的包的包装数量
                //    sqlMain += @" update PB_Stock set StockNumber=IFNULL(StockNumber,0)+1 where PackId='" + unpackdata.PackId + "'; ";
                //    //删除下架扫码记录
                //    sqlMain += @" delete from PB_UnLoadList where JobId='" + jobid + "'; ";
                //    //删除拆包记录
                //    sqlMain += @" delete from PB_UnpackingDetail where Id='" + unpackdata.Id + "'; ";
                //    sqlMain += @" delete from PB_Unpacking where Id='" + unpackdata.ParentId + "'; ";

                //    //增加入库日志
                //    PB_StockLog stocklog = new PB_StockLog();
                //    stocklog.Id = IdHelper.GetId();
                //    stocklog.PackId = unpackdata.PackId;
                //    stocklog.MaterialId = picklist.MaterialId;
                //    stocklog.StorId = locadata.StorId;
                //    stocklog.LocationId = picklist.LocationId;
                //    stocklog.StockNumber = 1;
                //    stocklog.CreatorId = _operator.UserId;
                //    stocklog.CreatorName = basedata.RealName;
                //    stocklog.CreateTime = DateTime.Now;
                //    stocklog.Type = 1;
                //    stocklog.OrderID = picklist.ParentId;
                //    stocklog.State = 0;
                //    stocklog.OldOrNew = unpackdata.OldOrNew;
                //    stocklog.CirBillId = "";
                //    stocklog.JobId = jobid;
                //    await Db.InsertAsync<PB_StockLog>(stocklog);

                //    await ExecuteSqlAsync(sqlMain);
                //}

                //获取成品码的下架记录
                Expression<Func<PB_UnLoadList, PB_Material, PB_Location, UnLoadListMaterialDTO>> select = (a, b, c) => new UnLoadListMaterialDTO
                {
                    MaterialName = b.Name,
                    Price = b.Price,
                    storageId = b.storageId,
                    StorId = c.StorId,
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_UnLoadList>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Material>() on a.ParentId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_Location>() on a.LocalId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        select @select.Invoke(a, b, c);
                var unjobdata = await q.Where(x => x.JobId == jobid).FirstOrDefaultAsync();
                if (unjobdata == null)
                {
                    throw new BusException("成品已移除不能重复移除");
                }

                PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();

                //恢复库存汇总数量
                if (jobdata.OldOrNew == 0)
                {
                    sqlMain += @"update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)+1,ScanNum=IFNULL(ScanNum,0)+1 where LocalId='" + unjobdata.LocalId + "' and MaterialId='" + unjobdata.MaterialId + "'; ";
                }
                else if (jobdata.OldOrNew == 1)
                {
                    sqlMain += @"update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+1,ScanNum=IFNULL(ScanNum,0)+1 where LocalId='" + unjobdata.LocalId + "' and MaterialId='" + unjobdata.MaterialId + "'; ";
                }

                PB_PickUpList PickUpList = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupid && x.MaterialId == unjobdata.MaterialId).FirstOrDefaultAsync();
                sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)+1 where MaterialId='" + unjobdata.MaterialId + "' and LocalId='" + PickUpList.LocationId + "'; ";


                //恢复物料的审核前数量
                sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)+1 where Id='" + unjobdata.MaterialId + "'; ";
                //修改备货单明细已备货数量
                sqlMain += @" update PB_PickUpList set ReadyNums=IFNULL(ReadyNums,0)-1 where Id='" + unjobdata.ParentId + "' and MaterialId='" + unjobdata.MaterialId + "'; ";
                //删除下架扫码记录
                sqlMain += @" delete from PB_UnLoadList where JobId='" + jobid + "'; ";
                var pb_PickListSteps = Db.GetIQueryable<PB_PickListSteps>().Where(x => x.ParentId == stockupid && x.MaterialId == unjobdata.MaterialId && x.ReadyNums != null && x.ReadyNums > 0 && x.LocationId == unjobdata.LocalId).ToList();

                if (pb_PickListSteps.Count > 0)
                {

                    sqlMain += " update  PB_PickListSteps set ReadyNums=IFNULL(ReadyNums,0)-1  where Id='" + pb_PickListSteps[pb_PickListSteps.Count - 1].Id + "'; ";
                }

                //库存明细表
                IT_LocalDetail detdata = new IT_LocalDetail();
                detdata.Id = IdHelper.GetId();
                detdata.StorId = unjobdata.StorId;
                detdata.LocalId = unjobdata.LocalId;
                detdata.MaterialId = unjobdata.MaterialId;
                detdata.MeasureId = unjobdata.storageId;
                detdata.InTime = DateTime.Now;
                detdata.CreateTime = DateTime.Now;
                detdata.CreatorId = _operator.UserId;
                detdata.Deleted = false;
                detdata.Num = 1;
                detdata.BarCode = h_FinishedProduct + "," + jobid;
                detdata.PackId = "";
                detdata.Price = unjobdata.Price;
                detdata.Amount = unjobdata.Price;
                detdata.OldOrNew = jobdata.OldOrNew;
                detdata.RecId = "";
                detdata.JobId = jobid;
                LocalDetailList.Add(detdata);

                //插入货架上存放货物存明细表
                PB_Stock stockdata = new PB_Stock();
                stockdata.Id = IdHelper.GetId();
                stockdata.PackId = "";
                stockdata.StorId = unjobdata.StorId;
                stockdata.LocationId = unjobdata.LocalId;
                stockdata.StockNumber = 1;
                stockdata.MaterialId = unjobdata.MaterialId;
                stockdata.CreatorId = _operator.UserId;
                stockdata.CreatorName = basedata.RealName;
                stockdata.CreateTime = DateTime.Now;
                stockdata.OperatorId = _operator.UserId;
                stockdata.OrderID = stockupid;
                stockdata.Type = 1;
                stockdata.OldOrNew = jobdata.OldOrNew;
                stockdata.CirBillId = "";
                stockdata.JobId = jobid;
                StockList.Add(stockdata);

                //增加入库日志
                PB_StockLog stocklog = new PB_StockLog();
                stocklog.Id = IdHelper.GetId();
                stocklog.PackId = "";
                stocklog.MaterialId = unjobdata.MaterialId;
                stocklog.StorId = unjobdata.StorId;
                stocklog.LocationId = unjobdata.LocalId;
                stocklog.StockNumber = 1;
                stocklog.CreatorId = _operator.UserId;
                stocklog.CreatorName = basedata.RealName;
                stocklog.CreateTime = DateTime.Now;
                stocklog.Type = 1;
                stocklog.OrderID = stockupid;
                stocklog.State = 0;
                stocklog.OldOrNew = jobdata.OldOrNew;
                stocklog.CirBillId = "";
                stocklog.JobId = jobid;
                StockLogList.Add(stocklog);

            }

            await Db.InsertAsync<PB_Stock>(StockList);

            await Db.InsertAsync<PB_StockLog>(StockLogList);

            await Db.InsertAsync<IT_LocalDetail>(LocalDetailList);

            await ExecuteSqlAsync(sqlMain);

        }

        /// <summary>
        /// 出库环节,获取包的信息
        /// </summary>
        /// <param name="PackQrcode">包二维码</param>
        /// <param name="stockupQrCode">备货单二维码</param>
        /// <returns></returns>
        public async Task<StockUpPackDTO> GetStockUpPackDataAsync(string PackQrcode, string stockupQrCode)
        {
            //包Id
            string packid = PackQrcode.Split(',')?[1].ToString();
            //备货单Id
            string stockupid = stockupQrCode.Split(',')?[1].ToString();

            PB_PackList packdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packid).FirstOrDefaultAsync();
            if (packdata != null)
            {
                if (packdata.Status == 5)
                {
                    throw new BusException("包码已作废,请做补码处理");
                }
                //Expression<Func<PB_PackMaterialCount, PB_Material, StockUpPackDetailDTO>> select = (a, b) => new StockUpPackDetailDTO
                //{
                //    PackId = a.PackId,
                //    MaterialId = a.MaterialId,
                //    MaterialName = b.Name,
                //    MaterialCode = b.Code,
                //    MaterialSpec = b.Spec,
                //    ProductCode = b.ProductCode,
                //    Nums = a.Nums
                //};
                //select = select.BuildExtendSelectExpre();
                //var q = from a in Db.GetIQueryable<PB_PackMaterialCount>().AsExpandable()
                //        join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                //        from b in ab.DefaultIfEmpty()
                //        select @select.Invoke(a, b);

                string sqlMain = @" select a.PackId,a.MaterialId,b.`Name` as MaterialName,b.`Code` as MaterialCode,b.Spec as MaterialSpec,b.ProductCode,a.Nums,(select SUM((StockVolume-ReadyNums)) from PB_PickUpList where ParentId='" + stockupid + "' and MaterialId=a.MaterialId) as RemainingQuantity from PB_PackMaterialCount as a left join PB_Material as b on a.MaterialId=b.Id where a.PackId='" + packid + "' ";

                List<StockUpPackDetailDTO> StockUpPackDetail = await Db.GetListBySqlAsync<StockUpPackDetailDTO>(sqlMain);
                StockUpPackDTO supack = new StockUpPackDTO();
                supack.PackId = packdata.Id;
                supack.PackQrCode = packdata.QrCode;
                supack.BoxName = packdata.BoxName;
                supack.Nums = packdata.Nums;
                supack.StockUpPackDetail = StockUpPackDetail;
                return supack;
            }
            else
            {
                throw new BusException("请扫描正确的包");
            }
        }

        /// <summary>
        /// 出库环节,获取单个成品物料信息
        /// </summary>
        /// <param name="JobQrCode">单个成品二维码</param>
        /// <param name="LocaQrcode">货位二维码</param>
        /// <param name="stockupQrCode">备货单二维码</param>
        /// <returns></returns>
        public async Task<StockMaterialDTO> GetStockMaterialDataAsync(string JobQrCode, string LocaQrcode, string stockupQrCode)
        {
            //单个成品Id
            string jobid = JobQrCode.Split(',')?[1].ToString();
            //货位Id
            string localId = LocaQrcode.Split(',')?[1].ToString();
            //备货单Id
            string stockupid = stockupQrCode.Split(',')?[1].ToString();
            //根据成品Id获取信息
            PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
            if (jobdata != null)
            {
                if (jobdata.PackStatus == 1)
                {
                    throw new BusException("成品码已作废,请做补码处理");
                }
                //查询备货单成品物料的备货信息
                PB_PickUpList PickUpList = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupid && x.MaterialId == jobdata.MaterialId).FirstOrDefaultAsync();
                if (PickUpList != null)
                {
                    //查询成品物料信息
                    PB_Material Material = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == jobdata.MaterialId).FirstOrDefaultAsync();
                    StockMaterialDTO StockMaterial = new StockMaterialDTO();
                    StockMaterial.MaterialId = jobdata.MaterialId;
                    StockMaterial.MaterialCode = Material.Code;
                    StockMaterial.MaterialName = Material.Name;
                    StockMaterial.MaterialSpec = Material.Spec;
                    StockMaterial.PackId = "";
                    StockMaterial.PackQrCode = "";
                    StockMaterial.Nums = 1;  //仓库内包外的成品物料数量
                    StockMaterial.RemainingQuantity = (PickUpList.StockVolume - (PickUpList.ReadyNums == null ? 0 : PickUpList.ReadyNums));  //备货剩余数量
                    return StockMaterial;
                }
                else
                {
                    throw new BusException("请检查物料与备货单物料是否匹配");
                }
            }
            else
            {
                throw new BusException("请检查成品码是否存在");
            }
        }

        /// <summary>
        /// 扫描包出库,并对备货单做对应物料数量做修改
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task UpdateStockUpDataAsync(OutStockData data)
        {
            AjaxResult ajaxr = new AjaxResult
            {
                ErrorCode = 1,
                Success = true,
                Msg = "接口异常"
            };
            try
            {
                //包编号
                string packid = string.Empty;
                //物料编号
                string materialId = string.Empty;
                //成品编码
                string jobid = string.Empty;
                string packmodel = string.Empty;
                Base_LinkType linktypedata = await _opdept.GetLinkType("MaterialCode");
                packmodel = data.packqrcode.Split(',')?[0].ToString();
                if (packmodel == "13")
                {
                    packid = data.packqrcode.Split(',')?[1].ToString();
                }
                else if (packmodel == "04")
                {
                    var model = data.packqrcode.Split(',');
                    if (model.Length > 2)
                    {
                        materialId = model?[3].ToString();
                    }
                    else
                    {
                        materialId = model?[1].ToString();
                    }
                    //合并重复物料指向新的物料Id
                    PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
                    if (!materdata.TransferId.IsNullOrEmpty())
                    {
                        materialId = materdata.TransferId;
                    }
                }
                else if (packmodel == "14")
                {
                    jobid = data.packqrcode.Split(',')?[1].ToString();
                    ////查询单个成品是否绑定包信息
                    //PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid && x.PackStatus == 0).FirstOrDefaultAsync();
                    //if (jobdata != null)
                    //{
                    //    if (!jobdata.PackId.IsNullOrEmpty())
                    //    {
                    //        packmodel = "13";
                    //        packid = jobdata.PackId;
                    //    }
                    //}
                }

                List<PB_UnLoadList> UnLoadList = new List<PB_UnLoadList>();
                List<PB_StockLog> StockLogList = new List<PB_StockLog>();
                List<PB_Unpacking> UnpackingList = new List<PB_Unpacking>();
                List<PB_UnpackingDetail> UnpackingDetailList = new List<PB_UnpackingDetail>();
                string sqlMain = string.Empty;

                Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
                //备货单编号
                string stockupQrCode = data.stockupQrCode.Split(',')?[1].ToString();

                List<TD_OutStorage> tD_OutStorages = await Db.GetIQueryable<TD_OutStorage>().Where(x => x.RefCode == stockupQrCode).ToListAsync();
                int outnum = tD_OutStorages.Count == 0 ? 1 : tD_OutStorages.Count + 1;

                //货位编号
                string locaId = data.locaqrcode.Split(',')?[1].ToString();

                if (packmodel == "13") //扫描包
                {
                    PB_PackList PB_PackListdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packid).FirstOrDefaultAsync();
                    if (PB_PackListdata == null)
                    {
                        ajaxr.ErrorCode = 0;
                        ajaxr.Success = false;
                        ajaxr.Msg = "请扫描正确的包二维码!";
                        throw new BusException(ajaxr.Msg);
                    }
                    if (PB_PackListdata.Status != 3)
                    {
                        ajaxr.ErrorCode = 0;
                        ajaxr.Success = false;
                        ajaxr.Msg = "请扫描仓库内的包!";
                        throw new BusException(ajaxr.Msg);
                    }
                    if (PB_PackListdata.PackageType == 0)
                    {
                        //获取仓库要出库的包信息
                        Expression<Func<IT_LocalDetail, PB_PackList, StockPackListDTO>> packselect = (a, b) => new StockPackListDTO
                        {
                            BoxName = b.BoxName,
                            PackageType = b.PackageType
                        };
                        packselect = packselect.BuildExtendSelectExpre();
                        var packdata = from a in Db.GetIQueryable<IT_LocalDetail>().AsExpandable()
                                       join b in Db.GetIQueryable<PB_PackList>() on a.PackId equals b.Id into ab
                                       from b in ab.DefaultIfEmpty()
                                       select @packselect.Invoke(a, b);
                        var pack = await packdata.Where(x => x.PackId == packid && x.LocalId == locaId).FirstOrDefaultAsync();
                        if (pack != null)
                        {
                            var trueorfalse = await _check.GetTrueOrFalse(pack.MaterialId, pack.StorId, locaId);
                            if (trueorfalse.boolType == false)
                            {
                                ajaxr.ErrorCode = 0;
                                ajaxr.Success = false;
                                ajaxr.Msg = "仓库物料正在盘点中禁止下架出库";
                                throw new BusException(ajaxr.Msg);
                            }

                            IT_LocalMaterial materdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == pack.MaterialId && x.StorId == pack.StorId && x.LocalId == pack.LocalId).FirstOrDefaultAsync();
                            if (materdata == null)
                            {
                                ajaxr.ErrorCode = 0;
                                ajaxr.Success = false;
                                ajaxr.Msg = "请检查库存物料是否存在";
                                throw new BusException(ajaxr.Msg);
                            }
                            else
                            {
                                double? dnum = materdata.Nums_O + materdata.Nums_N;
                                if (pack.Num > dnum)
                                {
                                    ajaxr.ErrorCode = 0;
                                    ajaxr.Success = false;
                                    ajaxr.Msg = "请检查库存物料数量是否满足!";
                                    throw new BusException(ajaxr.Msg);
                                }
                            }

                            //获取备货单明细信息
                            var detaildata = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupQrCode && x.MaterialId == pack.MaterialId).FirstOrDefaultAsync();
                            if (detaildata != null)
                            {
                                double? dnum = 0;
                                if (detaildata.ReadyNums.ToString().IsNullOrEmpty())
                                {
                                    dnum = PB_PackListdata.Nums;
                                }
                                else
                                {
                                    dnum = detaildata.ReadyNums + PB_PackListdata.Nums;
                                }
                                if (dnum > detaildata.StockVolume)
                                {
                                    ajaxr.ErrorCode = 0;
                                    ajaxr.Success = false;
                                    ajaxr.Msg = "物料数量大于备货单物料的剩余备货数量或请核对成品对应的包信息";
                                    throw new BusException(ajaxr.Msg);
                                }

                                //if (detaildata.ReadyNums == null)
                                //{
                                //    detaildata.ReadyNums = 0;
                                //}
                                ////备货单剩余备货数量
                                //double? surplusnum = detaildata.StockVolume - detaildata.ReadyNums;
                                ////判断：包的物料数量大于备货单剩余备货数量
                                //if (pack.Num > surplusnum)
                                //{
                                //    throw new BusException("包的物料数量大于备货单物料的剩余备货数量");
                                //}

                                //增加备货单明细日志
                                PB_UnLoadList pbdata = new PB_UnLoadList();
                                pbdata.Id = IdHelper.GetId();
                                pbdata.ParentId = detaildata.Id;
                                pbdata.LocalId = pack.LocalId;
                                pbdata.PackId = packid;
                                pbdata.MaterialId = detaildata.MaterialId;
                                pbdata.Nums = pack.Num;
                                pbdata.CreatorId = _operator.UserId;
                                pbdata.CreatorRealName = bdata.RealName;
                                pbdata.CreateTime = DateTime.Now;
                                pbdata.Deleted = false;
                                pbdata.JobId = "";
                                pbdata.OutNum = outnum;
                                UnLoadList.Add(pbdata);
                                //增加出库日志
                                PB_StockLog pblog = new PB_StockLog();
                                pblog.Id = IdHelper.GetId();
                                pblog.PackId = pack.PackId;
                                pblog.MaterialId = pack.MaterialId;
                                pblog.StorId = pack.StorId;
                                pblog.LocationId = pack.LocalId;
                                pblog.StockNumber = pack.Num;
                                pblog.CreatorId = _operator.UserId;
                                pblog.CreatorName = bdata.RealName;
                                pblog.OperatorId = _operator.UserId;
                                pblog.Type = 1;
                                pblog.OrderID = stockupQrCode;
                                pblog.CreateTime = DateTime.Now;
                                pblog.State = 1;
                                pblog.JobId = "";
                                StockLogList.Add(pblog);

                                //获取货位信息
                                var locationdata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == pack.LocalId).FirstOrDefaultAsync();

                                //删除库存
                                sqlMain += @" delete from PB_Stock where PackId='" + pack.PackId + "'; ";

                                //删除库存明细表
                                sqlMain += @" delete from IT_LocalDetail where PackId='" + pack.PackId + "'; ";

                                //修改货架上存放货物存汇总表的审核前数量和新旧数量
                                if (pack.OldOrNew == 0)
                                {
                                    //减去当前货位上的物料库存数量
                                    sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + pack.Num + ",ScanNum=IFNULL(ScanNum,0)-" + pack.Num + " where StorId='" + locationdata.StorId + "' and LocalId='" + locationdata.Id + "' and MaterialId='" + pack.MaterialId + "'; ";
                                }
                                else if (pack.OldOrNew == 1)
                                {
                                    sqlMain += @"update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + pack.Num + ",ScanNum=IFNULL(ScanNum,0)-" + pack.Num + " where StorId='" + locationdata.StorId + "' and LocalId='" + locationdata.Id + "' and MaterialId='" + pack.MaterialId + "'; ";
                                }

                                IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == pack.MaterialId && x.LocalId == detaildata.LocationId).FirstOrDefaultAsync();
                                if (LocalMaterial != null)
                                {
                                    if (pack.Num >= LocalMaterial.Nums_R)
                                    {
                                        //减去备货单物料对应货位的占用量
                                        sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + LocalMaterial.Nums_R + " where LocalId='" + detaildata.LocationId + "' and MaterialId='" + pack.MaterialId + "';";
                                    }
                                    else
                                    {
                                        //if (LocalMaterial.Nums_R < pack.Num)
                                        //{
                                        //    //减去备货单物料对应货位的占用量
                                        //    sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + LocalMaterial.Nums_R + " where LocalId='" + detaildata.LocationId + "' and MaterialId='" + pack.MaterialId + "';";
                                        //}
                                        //else
                                        //{
                                        //    //减去备货单物料对应货位的占用量
                                        //    sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + pack.Num + " where LocalId='" + detaildata.LocationId + "' and MaterialId='" + pack.MaterialId + "';";
                                        //}
                                        //减去备货单物料对应货位的占用量
                                        sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + pack.Num + " where LocalId='" + detaildata.LocationId + "' and MaterialId='" + pack.MaterialId + "';";
                                    }
                                }

                                //修改物料审核前数量
                                sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)-" + pack.Num + " where Id='" + detaildata.MaterialId + "'; ";

                                //修改备货单物料的已备货数量
                                sqlMain += @" update PB_PickUpList set ReadyNums=IFNULL(ReadyNums,0)+" + pack.Num + " where Id='" + detaildata.Id + "'; ";
                                //修改包的状态为已出库
                                sqlMain += @" update PB_PackList set Status=4,OutStorTime=NOW(),OutStorUserId='" + _operator.UserId + "',OutStorUserName='" + bdata.RealName + "' where Id='" + pack.PackId + "'; ";
                                //反写备货单明细分表对应已备货数量
                                var pb_PickListSteps = Db.GetIQueryable<PB_PickListSteps>().Where(x => x.ParentId == stockupQrCode && x.MaterialId == pack.MaterialId && x.LocationId == detaildata.LocationId && x.StockVolume > x.ReadyNums).ToList();
                                if (pb_PickListSteps.Count > 0)
                                {
                                    Boolean isfal = false;
                                    double? PackNums = pack.Num;
                                    foreach (var item in pb_PickListSteps)
                                    {
                                        var pb = await Db.GetIQueryable<PB_PickListSteps>().Where(m => m.Id == item.Id).FirstOrDefaultAsync();
                                        double? number = pb.StockVolume - (pb.ReadyNums == null ? 0 : pb.ReadyNums);
                                        PackNums = PackNums - number;
                                        if (isfal == false)
                                        {

                                            if (PackNums <= 0)
                                            {
                                                double? ASS = PackNums + pb.StockVolume;
                                                sqlMain += "update  PB_PickListSteps set ReadyNums=" + ASS + " where Id='" + item.Id + "'; ";

                                                isfal = true;
                                            }
                                            else
                                            {
                                                sqlMain += "update  PB_PickListSteps set ReadyNums=StockVolume where Id='" + item.Id + "'; ";

                                            }
                                        }

                                    }
                                }
                            }
                            else
                            {
                                ajaxr.ErrorCode = 0;
                                ajaxr.Success = false;
                                ajaxr.Msg = "请核对备货单物料与包对应的物料是否一致";
                                throw new BusException(ajaxr.Msg);
                            }
                        }
                        else
                        {
                            ajaxr.ErrorCode = 0;
                            ajaxr.Success = false;
                            ajaxr.Msg = "请扫描正确的货位上的包信息";
                            throw new BusException(ajaxr.Msg);
                        }
                    }
                    else if (PB_PackListdata.PackageType == 1)
                    {
                        //获取仓库要出库的包信息
                        Expression<Func<IT_LocalDetail, PB_PackList, PB_PickUpList, StockPackListDTO>> packselect = (a, b, c) => new StockPackListDTO
                        {
                            BoxName = b.BoxName,
                            PackageType = b.PackageType,
                            PickUpMainId = c.ParentId,
                            PickUpListId = c.Id,
                            StockVolume = c.StockVolume,
                            ReadyNums = c.ReadyNums
                        };
                        packselect = packselect.BuildExtendSelectExpre();
                        var packdata = from a in Db.GetIQueryable<IT_LocalDetail>().AsExpandable()
                                       join b in Db.GetIQueryable<PB_PackList>() on a.PackId equals b.Id into ab
                                       from b in ab.DefaultIfEmpty()
                                       join c in Db.GetIQueryable<PB_PickUpList>() on a.MaterialId equals c.MaterialId into ac
                                       from c in ac.DefaultIfEmpty()
                                       select @packselect.Invoke(a, b, c);
                        var pack = await packdata.Where(x => x.PackId == packid && x.PickUpMainId == stockupQrCode && x.LocalId == locaId).ToListAsync();

                        List<PB_PickUpList> pickuplist = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupQrCode).ToListAsync();
                        List<IT_LocalDetail> LocalDetaillist = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == packid).ToListAsync();
                        bool torf = true;

                        foreach (var item in LocalDetaillist)
                        {
                            var itemlist = pickuplist.Where(x => x.MaterialId == item.MaterialId).FirstOrDefault();
                            if (itemlist == null)
                            {
                                torf = false;
                            }
                        }
                        if (torf == false)
                        {
                            ajaxr.ErrorCode = 0;
                            ajaxr.Success = false;
                            ajaxr.Msg = "请检查包与备货单的物料是否匹配";
                            throw new BusException(ajaxr.Msg);
                        }
                        if (pack.Count > 0)
                        {
                            string strLocalId = string.Empty;
                            string strStorId = string.Empty;
                            foreach (var item in pack)
                            {
                                strLocalId = item.LocalId;
                                strStorId = item.StorId;
                                var trueorfalse = await _check.GetTrueOrFalse(item.MaterialId, item.StorId, item.LocalId);
                                if (trueorfalse.boolType == false)
                                {
                                    ajaxr.ErrorCode = 0;
                                    ajaxr.Success = false;
                                    ajaxr.Msg = "仓库物料正在盘点中禁止下架出库";
                                    throw new BusException(ajaxr.Msg);
                                }
                                IT_LocalMaterial materdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == item.MaterialId && x.StorId == item.StorId && x.LocalId == item.LocalId).FirstOrDefaultAsync();
                                if (materdata == null)
                                {
                                    ajaxr.ErrorCode = 0;
                                    ajaxr.Success = false;
                                    ajaxr.Msg = "请检查库存物料是否存在";
                                    throw new BusException(ajaxr.Msg);
                                }
                                else
                                {
                                    double? dnum = materdata.Nums_O + materdata.Nums_N;
                                    if (item.Num > dnum)
                                    {
                                        ajaxr.ErrorCode = 0;
                                        ajaxr.Success = false;
                                        ajaxr.Msg = "请检查库存物料数量是否满足!";
                                        throw new BusException(ajaxr.Msg);
                                    }
                                }
                                if ((Convert.ToDouble(item.ReadyNums) + item.Num) > item.StockVolume)
                                {
                                    ajaxr.ErrorCode = 0;
                                    ajaxr.Success = false;
                                    ajaxr.Msg = "物料数量大于备货单物料的剩余备货数量";
                                    throw new BusException(ajaxr.Msg);
                                }
                                //获取货位信息
                                var locationdata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == item.LocalId).FirstOrDefaultAsync();

                                //修改货架上存放货物存汇总表的审核前数量和新旧数量
                                if (item.OldOrNew == 0)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                }
                                else if (item.OldOrNew == 1)
                                {
                                    sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                }

                                IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == item.MaterialId && x.LocalId == item.LocalId).FirstOrDefaultAsync();
                                if (LocalMaterial != null)
                                {
                                    if (item.Num >= LocalMaterial.Nums_R)
                                    {
                                        //减去备货单物料对应货位的占用量
                                        sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + LocalMaterial.Nums_R + " where  LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "';";
                                    }
                                    else
                                    {
                                        //if (LocalMaterial.Nums_R < item.Num)
                                        //{
                                        //    //减去备货单物料对应货位的占用量
                                        //    sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + LocalMaterial.Nums_R + " where  LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "';";
                                        //}
                                        //else
                                        //{
                                        //    //减去备货单物料对应货位的占用量
                                        //    sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + item.Num + " where  LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "';";
                                        //}
                                        //减去备货单物料对应货位的占用量
                                        sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + item.Num + " where  LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "';";
                                    }
                                }

                                //修改物料审核前数量
                                sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where Id='" + item.MaterialId + "'; ";

                                //修改备货单物料的已备货数量
                                sqlMain += @" update PB_PickUpList set ReadyNums=IFNULL(ReadyNums,0)+" + item.Num + " where ParentId='" + stockupQrCode + "' and MaterialId='" + item.MaterialId + "'; ";

                                //反写设计清单步级已备货数量

                                //增加备货单明细日志
                                PB_UnLoadList pbdata = new PB_UnLoadList();
                                pbdata.Id = IdHelper.GetId();
                                pbdata.ParentId = item.PickUpListId;
                                pbdata.LocalId = item.LocalId;
                                pbdata.PackId = packid;
                                pbdata.MaterialId = item.MaterialId;
                                pbdata.Nums = item.Num;
                                pbdata.CreatorId = _operator.UserId;
                                pbdata.CreatorRealName = bdata.RealName;
                                pbdata.CreateTime = DateTime.Now;
                                pbdata.Deleted = false;
                                pbdata.JobId = "";
                                pbdata.OutNum = outnum;
                                UnLoadList.Add(pbdata);
                            }
                            //增加出库日志
                            PB_StockLog pblog = new PB_StockLog();
                            pblog.Id = IdHelper.GetId();
                            pblog.PackId = packid;
                            pblog.MaterialId = "";
                            pblog.StorId = strStorId;
                            pblog.LocationId = strLocalId;
                            pblog.StockNumber = PB_PackListdata.Nums;
                            pblog.CreatorId = _operator.UserId;
                            pblog.CreatorName = bdata.RealName;
                            pblog.OperatorId = _operator.UserId;
                            pblog.Type = 1;
                            pblog.OrderID = stockupQrCode;
                            pblog.CreateTime = DateTime.Now;
                            pblog.State = 1;
                            pblog.JobId = "";
                            StockLogList.Add(pblog);

                            //删除库存
                            sqlMain += @" delete from PB_Stock where PackId='" + packid + "'; ";

                            //删除库存明细表
                            sqlMain += @" delete from IT_LocalDetail where PackId='" + packid + "'; ";

                            //修改包的状态为已出库
                            sqlMain += @" update PB_PackList set Status=4,OutStorTime=NOW(),OutStorUserId='" + _operator.UserId + "',OutStorUserName='" + bdata.RealName + "' where Id='" + packid + "'; ";
                        }
                        else
                        {
                            ajaxr.ErrorCode = 0;
                            ajaxr.Success = false;
                            ajaxr.Msg = "请扫描正确的货位上的包信息";
                            throw new BusException(ajaxr.Msg);
                        }
                    }
                }
                else if (packmodel == "04") //扫描单个物料
                {
                    List<IT_LocalDetail> IT_LocalDetaillist = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.MaterialId == materialId && x.PackId == "" && x.LocalId == locaId).ToListAsync();
                    if (IT_LocalDetaillist.Count > 0)
                    {
                        //汇总当前货位的物料总数量
                        var matersumnums = IT_LocalDetaillist.GroupBy(x => new { x.MaterialId, x.StorId, x.LocalId }).Select(x => new { MaterialId = x.Key.MaterialId, LocalId = x.Key.LocalId, StorId = x.Key.StorId, materNums = x.Sum(i => i.Num) }).FirstOrDefault();
                        if (data.Nums > matersumnums.materNums)
                        {
                            ajaxr.ErrorCode = 0;
                            ajaxr.Success = false;
                            ajaxr.Msg = "请检查当前货位物料的数量是否满足出库的数量";
                            throw new BusException(ajaxr.Msg);
                        }

                        //获取备货单明细信息
                        var detaildata = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupQrCode && x.MaterialId == materialId && x.LocationId == locaId).FirstOrDefaultAsync();
                        if (detaildata.IsNullOrEmpty())
                        {
                            ajaxr.ErrorCode = 0;
                            ajaxr.Success = false;
                            ajaxr.Msg = "请检查扫描的物料是否存在备货单中";
                            throw new BusException(ajaxr.Msg);
                        }
                        double? dnum = 0;
                        if (detaildata.ReadyNums.ToString().IsNullOrEmpty())
                        {
                            dnum = data.Nums;
                        }
                        else
                        {
                            dnum = detaildata.ReadyNums + data.Nums;
                        }
                        if (dnum > detaildata.StockVolume)
                        {
                            ajaxr.ErrorCode = 0;
                            ajaxr.Success = false;
                            ajaxr.Msg = "物料数量大于备货单物料的剩余备货数量";
                            throw new BusException(ajaxr.Msg);
                        }
                        //获取要出库的单个物料数量
                        double? warehouseNum = data.Nums;

                        IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == materialId && x.LocalId == locaId).FirstOrDefaultAsync();

                        string itsql = string.Empty;
                        string strLocalId = string.Empty;
                        string strStorId = string.Empty;
                        foreach (var item in IT_LocalDetaillist)
                        {
                            var trueorfalse = await _check.GetTrueOrFalse(item.MaterialId, item.StorId, item.LocalId);
                            if (trueorfalse.boolType == false)
                            {
                                ajaxr.ErrorCode = 0;
                                ajaxr.Success = false;
                                ajaxr.Msg = "仓库物料正在盘点中禁止下架出库";
                                throw new BusException(ajaxr.Msg);
                            }
                            if (warehouseNum > 0)
                            {
                                strLocalId = item.LocalId;
                                strStorId = item.StorId;
                                //出库数量等于库存明细数量时
                                if (item.Num == warehouseNum)
                                {
                                    warehouseNum -= item.Num;
                                    if (item.OldOrNew == 0)
                                    {
                                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                    }
                                    else if (item.OldOrNew == 1)
                                    {
                                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                    }
                                    sqlMain += @" delete from IT_LocalDetail where Id='" + item.Id + "'; ";
                                    //IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == item.MaterialId && x.LocalId == item.LocalId).FirstOrDefaultAsync();
                                    //if (LocalMaterial != null)
                                    //{
                                    //    if (item.Num > LocalMaterial.Nums_R)
                                    //    {
                                    //        //减去备货单物料对应货位的占用量
                                    //        sqlMain += @" update IT_LocalMaterial set Nums_R=0 where  LocalId='" + detaildata.LocationId + "' and MaterialId='" + item.MaterialId + "';";
                                    //    }
                                    //    else
                                    //    {
                                    //        if (LocalMaterial.Nums_R < item.Num)
                                    //        {
                                    //            //减去备货单物料对应货位的占用量
                                    //            sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + LocalMaterial.Nums_R + " where  LocalId='" + detaildata.LocationId + "' and MaterialId='" + item.MaterialId + "';";
                                    //        }
                                    //        else
                                    //        {
                                    //            //减去备货单物料对应货位的占用量
                                    //            sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + item.Num + " where  LocalId='" + detaildata.LocationId + "' and MaterialId='" + item.MaterialId + "';";
                                    //        }
                                    //    }
                                    //}
                                }
                                else if (item.Num < warehouseNum)   //出库数量大于库存明细数量时
                                {
                                    if (warehouseNum >= item.Num)
                                    {
                                        warehouseNum -= item.Num;
                                        if (item.OldOrNew == 0)
                                        {
                                            sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                        }
                                        else if (item.OldOrNew == 1)
                                        {
                                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + item.Num + ",ScanNum=IFNULL(ScanNum,0)-" + item.Num + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                        }
                                        sqlMain += @" delete from IT_LocalDetail where Id='" + item.Id + "'; ";
                                        //IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == item.MaterialId && x.LocalId == item.LocalId).FirstOrDefaultAsync();
                                        //if (LocalMaterial != null)
                                        //{
                                        //    if (item.Num > LocalMaterial.Nums_R)
                                        //    {
                                        //        //减去备货单物料对应货位的占用量
                                        //        sqlMain += @" update IT_LocalMaterial set Nums_R=0 where  LocalId='" + detaildata.LocationId + "' and MaterialId='" + item.MaterialId + "';";
                                        //    }
                                        //    else
                                        //    {
                                        //        if (LocalMaterial.Nums_R < item.Num)
                                        //        {
                                        //            //减去备货单物料对应货位的占用量
                                        //            sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + LocalMaterial.Nums_R + " where  LocalId='" + detaildata.LocationId + "' and MaterialId='" + item.MaterialId + "';";
                                        //        }
                                        //        else
                                        //        {
                                        //            //减去备货单物料对应货位的占用量
                                        //            sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + item.Num + " where  LocalId='" + detaildata.LocationId + "' and MaterialId='" + item.MaterialId + "';";
                                        //        }
                                        //    }
                                        //}

                                    }
                                    else
                                    {
                                        if (item.OldOrNew == 0)
                                        {
                                            sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                        }
                                        else if (item.OldOrNew == 1)
                                        {
                                            sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                        }
                                        sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + warehouseNum + " where Id='" + item.Id + "'; ";
                                        //IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == item.MaterialId && x.LocalId == item.LocalId).FirstOrDefaultAsync();
                                        //if (LocalMaterial != null)
                                        //{
                                        //    if (warehouseNum > LocalMaterial.Nums_R)
                                        //    {
                                        //        //减去备货单物料对应货位的占用量
                                        //        sqlMain += @" update IT_LocalMaterial set Nums_R=0 where  LocalId='" + detaildata.LocationId + "' and MaterialId='" + item.MaterialId + "';";
                                        //    }
                                        //    else
                                        //    {
                                        //        if (LocalMaterial.Nums_R < warehouseNum)
                                        //        {
                                        //            //减去备货单物料对应货位的占用量
                                        //            sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + LocalMaterial.Nums_R + " where  LocalId='" + detaildata.LocationId + "' and MaterialId='" + item.MaterialId + "';";
                                        //        }
                                        //        else
                                        //        {
                                        //            //减去备货单物料对应货位的占用量
                                        //            sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + warehouseNum + " where  LocalId='" + detaildata.LocationId + "' and MaterialId='" + item.MaterialId + "';";
                                        //        }
                                        //    }
                                        //}
                                        warehouseNum -= warehouseNum;
                                    }
                                }
                                else if (item.Num > warehouseNum) //出库数量小于库存明细数量时
                                {
                                    item.Num -= warehouseNum;
                                    if (item.OldOrNew == 0)
                                    {
                                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                    }
                                    else if (item.OldOrNew == 1)
                                    {
                                        sqlMain += @" update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-" + warehouseNum + ",ScanNum=IFNULL(ScanNum,0)-" + warehouseNum + " where StorId='" + item.StorId + "' and LocalId='" + item.LocalId + "' and MaterialId='" + item.MaterialId + "'; ";
                                    }
                                    sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + warehouseNum + " where Id='" + item.Id + "'; ";
                                    //IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == item.MaterialId && x.LocalId == item.LocalId).FirstOrDefaultAsync();
                                    //if (LocalMaterial != null)
                                    //{
                                    //    if (warehouseNum > LocalMaterial.Nums_R)
                                    //    {
                                    //        //减去备货单物料对应货位的占用量
                                    //        sqlMain += @" update IT_LocalMaterial set Nums_R=0 where  LocalId='" + detaildata.LocationId + "' and MaterialId='" + item.MaterialId + "';";
                                    //    }
                                    //    else
                                    //    {
                                    //        //减去备货单物料对应货位的占用量
                                    //        sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + warehouseNum + " where  LocalId='" + detaildata.LocationId + "' and MaterialId='" + item.MaterialId + "';";
                                    //    }
                                    //}
                                    warehouseNum -= warehouseNum;
                                }

                            }
                            else
                            {
                                continue;
                            }
                        }

                        if (!LocalMaterial.IsNullOrEmpty())
                        {
                            //本次出库数量大于等于库存占用量
                            if (data.Nums >= LocalMaterial.Nums_R)
                            {
                                //减去备货单物料对应货位的占用量
                                sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + LocalMaterial.Nums_R + " where  LocalId='" + locaId + "' and MaterialId='" + materialId + "';";
                            }
                            else
                            {
                                //减去备货单物料对应货位的占用量
                                sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + data.Nums + " where  LocalId='" + locaId + "' and MaterialId='" + materialId + "';";
                            }
                        }

                        sqlMain += @" update PB_PickUpList set ReadyNums=IFNULL(ReadyNums,0)+" + data.Nums + " where Id='" + detaildata.Id + "' and ParentId='" + stockupQrCode + "' and MaterialId='" + materialId + "' ; ";
                        var pb_PickListSteps = Db.GetIQueryable<PB_PickListSteps>().Where(x => x.ParentId == stockupQrCode && x.MaterialId == materialId && x.LocationId == strLocalId && x.StockVolume > x.ReadyNums).ToList();
                        if (pb_PickListSteps.Count > 0)
                        {
                            Boolean isfal = false;
                            double? PackNums = data.Nums;
                            foreach (var item in pb_PickListSteps)
                            {
                                var pb = await Db.GetIQueryable<PB_PickListSteps>().Where(m => m.Id == item.Id).FirstOrDefaultAsync();
                                double? number = pb.StockVolume - (pb.ReadyNums == null ? 0 : pb.ReadyNums);
                                PackNums = PackNums - number;
                                if (isfal == false)
                                {

                                    if (PackNums <= 0)
                                    {
                                        double? ASS = PackNums + pb.StockVolume;
                                        sqlMain += "update  PB_PickListSteps set ReadyNums=" + ASS + " where Id='" + item.Id + "';";

                                        isfal = true;
                                    }
                                    else
                                    {
                                        sqlMain += "update  PB_PickListSteps set ReadyNums=StockVolume where Id='" + item.Id + "';";

                                    }
                                }

                            }
                        }
                        //增加备货单明细日志
                        PB_UnLoadList pbdata = new PB_UnLoadList();
                        pbdata.Id = IdHelper.GetId();
                        pbdata.ParentId = detaildata.Id;
                        pbdata.LocalId = strLocalId;
                        pbdata.PackId = "";
                        pbdata.MaterialId = materialId;
                        pbdata.Nums = data.Nums;
                        pbdata.CreatorId = _operator.UserId;
                        pbdata.CreatorRealName = bdata.RealName;
                        pbdata.CreateTime = DateTime.Now;
                        pbdata.Deleted = false;
                        pbdata.JobId = "";
                        pbdata.OutNum = outnum;
                        UnLoadList.Add(pbdata);
                        //增加出库日志
                        PB_StockLog pblog = new PB_StockLog();
                        pblog.Id = IdHelper.GetId();
                        pblog.PackId = packid;
                        pblog.StorId = strStorId;
                        pblog.LocationId = strLocalId;
                        pblog.MaterialId = materialId;
                        pblog.StockNumber = data.Nums;
                        pblog.CreatorId = _operator.UserId;
                        pblog.CreatorName = bdata.RealName;
                        pblog.OperatorId = _operator.UserId;
                        pblog.Type = 1;
                        pblog.OrderID = stockupQrCode;
                        pblog.CreateTime = DateTime.Now;
                        pblog.State = 1;
                        pblog.JobId = "";
                        StockLogList.Add(pblog);
                    }
                    else
                    {
                        ajaxr.ErrorCode = 0;
                        ajaxr.Success = false;
                        ajaxr.Msg = "请检查货位上的库存物料是否满足需求";
                        throw new BusException(ajaxr.Msg);
                    }

                }
                else if (packmodel == "14") //扫描成品物料
                {
                    if (linktypedata.Whether == true)
                    {
                        IT_LocalDetail LocalDetaildata = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.JobId == jobid).FirstOrDefaultAsync();
                        //库存不存在需要拆包
                        if (LocalDetaildata == null)
                        {
                            //获取成品信息
                            PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
                            if (jobdata == null)
                            {
                                ajaxr.ErrorCode = 0;
                                ajaxr.Success = false;
                                ajaxr.Msg = "请检查成品码是否有效";
                                throw new BusException(ajaxr.Msg);
                            }

                            //获取备货单明细信息
                            var detaildata = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupQrCode && x.MaterialId == jobdata.MaterialId).FirstOrDefaultAsync();
                            if (detaildata == null)
                            {
                                ajaxr.ErrorCode = 0;
                                ajaxr.Success = false;
                                ajaxr.Msg = "请检查扫描的成品是否存在备货单中";
                                throw new BusException(ajaxr.Msg);
                            }

                            PB_UnLoadList UnLoadListdata = await Db.GetIQueryable<PB_UnLoadList>().Where(x => x.JobId == jobid).FirstOrDefaultAsync();
                            if (UnLoadListdata != null)
                            {
                                ajaxr.ErrorCode = 0;
                                ajaxr.Success = false;
                                ajaxr.Msg = "请勿重复扫描出库";
                                throw new BusException(ajaxr.Msg);
                            }

                            double? dnum = 0;
                            if (detaildata.ReadyNums.ToString().IsNullOrEmpty())
                            {
                                dnum = 1;
                            }
                            else
                            {
                                dnum = detaildata.ReadyNums + 1;
                            }
                            if (dnum > detaildata.StockVolume)
                            {
                                ajaxr.ErrorCode = 0;
                                ajaxr.Success = false;
                                ajaxr.Msg = "物料数量大于备货单物料的剩余备货数量";
                                throw new BusException(ajaxr.Msg);
                            }

                            if (!jobdata.PackId.IsNullOrEmpty())
                            {
                                PB_PackList packdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == jobdata.PackId).FirstOrDefaultAsync();
                                if (packdata.Status == 4)
                                {
                                    ajaxr.ErrorCode = 0;
                                    ajaxr.Success = false;
                                    ajaxr.Msg = "成品码对应包已出库";
                                    throw new BusException(ajaxr.Msg);
                                }
                                if (packdata.Nums == 1)
                                {
                                    ajaxr.ErrorCode = 0;
                                    ajaxr.Success = false;
                                    ajaxr.Msg = "包不允许拆包,请扫描包出库";
                                    throw new BusException(ajaxr.Msg);
                                }

                                #region  默认自动拆包

                                //拆包日志主表
                                PB_Unpacking unpack = new PB_Unpacking();
                                string unpackid = IdHelper.GetId();
                                unpack.Id = unpackid;
                                unpack.PrimaryPackId = jobdata.PackId;
                                unpack.Nums = 1;
                                unpack.OperatorUserId = _operator.UserId;
                                unpack.OperatorUserName = bdata.RealName;
                                unpack.CreateTime = DateTime.Now;
                                unpack.Deleted = false;
                                unpack.Type = 2;
                                UnpackingList.Add(unpack);

                                //拆包日志明细表
                                PB_UnpackingDetail undetail = new PB_UnpackingDetail();
                                undetail.Id = IdHelper.GetId();
                                undetail.ParentId = unpackid;
                                undetail.JobBookingId = jobid;
                                undetail.OldOrNew = jobdata.OldOrNew;
                                undetail.CreatorId = _operator.UserId;
                                undetail.CreatorRealName = bdata.RealName;
                                undetail.CreateTime = DateTime.Now;
                                undetail.Deleted = false;
                                undetail.PickMainId = detaildata.ParentId;
                                undetail.PickListId = detaildata.Id;
                                undetail.MaterialId = jobdata.MaterialId;
                                UnpackingDetailList.Add(undetail);


                                //删除成品与包的关系
                                sqlMain += @" update PB_JobBookingQrCode set PackId='' where Id='" + jobid + "'; ";
                                //删除包明细与成品的关系
                                sqlMain += @" DELETE from PB_PackListInfo where PackId='" + jobdata.PackId + "' and JobBookingId='" + jobid + "'; ";
                                //修改包的包装数量
                                sqlMain += @" update PB_PackList set Nums=IFNULL(Nums,0)-1 where Id='" + jobdata.PackId + "'; ";
                                //修改包的包装数量
                                sqlMain += @" update PB_PackMaterialCount set Nums=IFNULL(Nums,0)-1 where PackId='" + jobdata.PackId + "' and MaterialId='" + jobdata.MaterialId + "'; ";

                                //await ExecuteSqlAsync(sqlMain);
                                #endregion

                                //查询仓库包信息
                                IT_LocalDetail LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == jobdata.PackId && x.LocalId == locaId).FirstOrDefaultAsync();
                                if (LocalDetail != null)
                                {
                                    var trueorfalse = await _check.GetTrueOrFalse(LocalDetail.MaterialId, LocalDetail.StorId, locaId);
                                    if (trueorfalse.boolType == false)
                                    {
                                        ajaxr.ErrorCode = 0;
                                        ajaxr.Success = false;
                                        ajaxr.Msg = "仓库物料正在盘点中禁止下架出库";
                                        throw new BusException(ajaxr.Msg);
                                    }
                                    IT_LocalMaterial materdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == LocalDetail.MaterialId && x.StorId == LocalDetail.StorId && x.LocalId == LocalDetail.LocalId).FirstOrDefaultAsync();
                                    if (materdata == null)
                                    {
                                        ajaxr.ErrorCode = 0;
                                        ajaxr.Success = false;
                                        ajaxr.Msg = "请检查库存物料是否存在";
                                        throw new BusException(ajaxr.Msg);
                                    }
                                    //修改库存汇总数量
                                    if (LocalDetail.OldOrNew == 0)
                                    {
                                        sqlMain += @"update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-1,ScanNum=IFNULL(ScanNum,0)-1 where StorId='" + LocalDetail.StorId + "' and LocalId='" + LocalDetail.LocalId + "' and MaterialId='" + LocalDetail.MaterialId + "'; ";
                                    }
                                    else if (LocalDetail.OldOrNew == 1)
                                    {
                                        sqlMain += @"update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-1,ScanNum=IFNULL(ScanNum,0)-1 where StorId='" + LocalDetail.StorId + "' and LocalId='" + LocalDetail.LocalId + "' and MaterialId='" + LocalDetail.MaterialId + "'; ";
                                    }
                                    if (materdata.Nums_R > 1)
                                    {
                                        //减去备货单物料对应货位的占用量
                                        sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-1 where  LocalId='" + detaildata.LocationId + "' and MaterialId='" + LocalDetail.MaterialId + "';";
                                    }
                                    else
                                    {
                                        //减去备货单物料对应货位的占用量
                                        sqlMain += @" update IT_LocalMaterial set Nums_R=0 where  LocalId='" + detaildata.LocationId + "' and MaterialId='" + LocalDetail.MaterialId + "';";
                                    }

                                    //修改物料档案审核前数量
                                    sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)-1 where Id='" + LocalDetail.MaterialId + "'; ";
                                    //修改库存明细成品对应包的数量
                                    sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-1 where PackId='" + LocalDetail.PackId + "' and LocalId='" + LocalDetail.LocalId + "'; ";
                                    //修改PB_Stock成品对应包的数量
                                    sqlMain += @" update PB_Stock set StockNumber=IFNULL(StockNumber,0)-1 where PackId='" + LocalDetail.PackId + "' and LocationId='" + LocalDetail.LocalId + "'; ";
                                    //修改备货单明细表的已备货数量
                                    sqlMain += @"update PB_PickUpList set ReadyNums=IFNULL(ReadyNums,0)+1 where ParentId='" + stockupQrCode + "' and MaterialId='" + LocalDetail.MaterialId + "' ; ";
                                    var pb_PickListSteps = Db.GetIQueryable<PB_PickListSteps>().Where(x => x.ParentId == stockupQrCode && x.MaterialId == LocalDetail.MaterialId && x.LocationId == LocalDetail.LocalId && x.StockVolume > x.ReadyNums).ToList();
                                    if (pb_PickListSteps.Count > 0)
                                    {


                                        sqlMain += "update  PB_PickListSteps set ReadyNums=IFNULL(ReadyNums,0)+1 where Id='" + pb_PickListSteps[0].Id + "';";


                                    }
                                    //增加备货单明细日志
                                    PB_UnLoadList pbdata = new PB_UnLoadList();
                                    pbdata.Id = IdHelper.GetId();
                                    pbdata.ParentId = detaildata.Id;
                                    pbdata.LocalId = LocalDetail.LocalId;
                                    pbdata.PackId = "";
                                    pbdata.MaterialId = LocalDetail.MaterialId;
                                    pbdata.Nums = 1;
                                    pbdata.CreatorId = _operator.UserId;
                                    pbdata.CreatorRealName = bdata.RealName;
                                    pbdata.CreateTime = DateTime.Now;
                                    pbdata.Deleted = false;
                                    pbdata.JobId = jobid;
                                    pbdata.OutNum = outnum;
                                    UnLoadList.Add(pbdata);

                                    //增加出库日志
                                    PB_StockLog pblog = new PB_StockLog();
                                    pblog.Id = IdHelper.GetId();
                                    pblog.PackId = "";
                                    pblog.MaterialId = jobdata.MaterialId;
                                    pblog.StorId = LocalDetail.StorId;
                                    pblog.LocationId = LocalDetail.LocalId;
                                    pblog.StockNumber = 1;
                                    pblog.CreatorId = _operator.UserId;
                                    pblog.CreatorName = bdata.RealName;
                                    pblog.OperatorId = _operator.UserId;
                                    pblog.Type = 1;
                                    pblog.OrderID = stockupQrCode;
                                    pblog.CreateTime = DateTime.Now;
                                    pblog.State = 1;
                                    pblog.JobId = jobid;
                                    StockLogList.Add(pblog);

                                }
                                else
                                {
                                    ajaxr.ErrorCode = 0;
                                    ajaxr.Success = false;
                                    ajaxr.Msg = "请扫描正确的货位上的成品信息";
                                    throw new BusException(ajaxr.Msg);
                                }
                            }
                            else
                            {
                                ajaxr.ErrorCode = 0;
                                ajaxr.Success = false;
                                ajaxr.Msg = "成品码已出库";
                                throw new BusException(ajaxr.Msg);
                            }
                        }
                        else  //库存存在单个成品
                        {
                            if (LocalDetaildata.LocalId != locaId)
                            {
                                ajaxr.ErrorCode = 0;
                                ajaxr.Success = false;
                                ajaxr.Msg = "请检查扫描的成品货位是否正确";
                                throw new BusException(ajaxr.Msg);
                            }
                            var trueorfalse = await _check.GetTrueOrFalse(LocalDetaildata.MaterialId, LocalDetaildata.StorId, locaId);
                            if (trueorfalse.boolType == false)
                            {
                                ajaxr.ErrorCode = 0;
                                ajaxr.Success = false;
                                ajaxr.Msg = "仓库物料正在盘点中禁止下架出库";
                                throw new BusException(ajaxr.Msg);
                            }
                            IT_LocalMaterial materdata = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == LocalDetaildata.MaterialId && x.StorId == LocalDetaildata.StorId && x.LocalId == LocalDetaildata.LocalId).FirstOrDefaultAsync();
                            if (materdata == null)
                            {
                                ajaxr.ErrorCode = 0;
                                ajaxr.Success = false;
                                ajaxr.Msg = "请检查库存物料是否存在";
                                throw new BusException(ajaxr.Msg);
                            }
                            //获取备货单明细信息
                            var detaildata = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupQrCode && x.MaterialId == LocalDetaildata.MaterialId).FirstOrDefaultAsync();
                            if (detaildata == null)
                            {
                                ajaxr.ErrorCode = 0;
                                ajaxr.Success = false;
                                ajaxr.Msg = "请检查扫描的成品是否存在备货单中";
                                throw new BusException(ajaxr.Msg);
                            }

                            double? dnum = 0;
                            if (detaildata.ReadyNums.ToString().IsNullOrEmpty())
                            {
                                dnum = 1;
                            }
                            else
                            {
                                dnum = detaildata.ReadyNums + 1;
                            }
                            if (dnum > detaildata.StockVolume)
                            {
                                ajaxr.ErrorCode = 0;
                                ajaxr.Success = false;
                                ajaxr.Msg = "物料数量大于备货单物料的剩余备货数量";
                                throw new BusException(ajaxr.Msg);
                            }
                            //修改库存汇总数量
                            if (LocalDetaildata.OldOrNew == 0)
                            {
                                sqlMain += @"update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-1,ScanNum=IFNULL(ScanNum,0)-1 where StorId='" + LocalDetaildata.StorId + "' and LocalId='" + LocalDetaildata.LocalId + "' and MaterialId='" + LocalDetaildata.MaterialId + "'; ";
                            }
                            else if (LocalDetaildata.OldOrNew == 1)
                            {
                                sqlMain += @"update IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)-1,ScanNum=IFNULL(ScanNum,0)-1 where StorId='" + LocalDetaildata.StorId + "' and LocalId='" + LocalDetaildata.LocalId + "' and MaterialId='" + LocalDetaildata.MaterialId + "'; ";
                            }
                            if (materdata.Nums_R > 1)
                            {
                                //减去备货单物料对应货位的占用量
                                sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-1 where  LocalId='" + detaildata.LocationId + "' and MaterialId='" + LocalDetaildata.MaterialId + "';";
                            }
                            else
                            {
                                //减去备货单物料对应货位的占用量
                                sqlMain += @" update IT_LocalMaterial set Nums_R=0 where  LocalId='" + detaildata.LocationId + "' and MaterialId='" + LocalDetaildata.MaterialId + "';";
                            }

                            //修改物料档案审核前数量
                            sqlMain += @" update PB_Material set ScanNum=IFNULL(ScanNum,0)-1 where Id='" + LocalDetaildata.MaterialId + "'; ";
                            //删除库存明细信息
                            sqlMain += @" delete from IT_LocalDetail where JobId='" + jobid + "'; ";
                            //修改PB_Stock成品对应包的数量
                            sqlMain += @" delete from PB_Stock where JobId='" + jobid + "'; ";
                            //修改备货单明细表的已备货数量
                            sqlMain += @" update PB_PickUpList set ReadyNums=IFNULL(ReadyNums,0)+1 where ParentId='" + stockupQrCode + "' and MaterialId='" + LocalDetaildata.MaterialId + "'; ";
                            var pb_PickListSteps = Db.GetIQueryable<PB_PickListSteps>().Where(x => x.ParentId == stockupQrCode && x.MaterialId == LocalDetaildata.MaterialId && x.LocationId == LocalDetaildata.LocalId && x.StockVolume > x.ReadyNums).ToList();
                            if (pb_PickListSteps.Count > 0)
                            {

                                sqlMain += "update  PB_PickListSteps set ReadyNums=IFNULL(ReadyNums,0)+1 where Id='" + pb_PickListSteps[0].Id + "'; ";

                            }
                            //增加备货单明细日志
                            PB_UnLoadList pbdata = new PB_UnLoadList();
                            pbdata.Id = IdHelper.GetId();
                            pbdata.ParentId = detaildata.Id;
                            pbdata.LocalId = LocalDetaildata.LocalId;
                            pbdata.PackId = "";
                            pbdata.MaterialId = LocalDetaildata.MaterialId;
                            pbdata.Nums = 1;
                            pbdata.CreatorId = _operator.UserId;
                            pbdata.CreatorRealName = bdata.RealName;
                            pbdata.CreateTime = DateTime.Now;
                            pbdata.Deleted = false;
                            pbdata.JobId = jobid;
                            pbdata.OutNum = outnum;
                            UnLoadList.Add(pbdata);

                            //增加出库日志
                            PB_StockLog pblog = new PB_StockLog();
                            pblog.Id = IdHelper.GetId();
                            pblog.PackId = "";
                            pblog.MaterialId = LocalDetaildata.MaterialId;
                            pblog.StorId = LocalDetaildata.StorId;
                            pblog.LocationId = LocalDetaildata.LocalId;
                            pblog.StockNumber = 1;
                            pblog.CreatorId = _operator.UserId;
                            pblog.CreatorName = bdata.RealName;
                            pblog.OperatorId = _operator.UserId;
                            pblog.Type = 1;
                            pblog.OrderID = stockupQrCode;
                            pblog.CreateTime = DateTime.Now;
                            pblog.State = 1;
                            pblog.JobId = jobid;
                            StockLogList.Add(pblog);
                        }
                    }
                    else
                    {
                        //查询成品物料信息
                        PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
                        if (jobdata == null)
                        {
                            ajaxr.ErrorCode = 0;
                            ajaxr.Success = false;
                            ajaxr.Msg = "请检查成品信息是否正确";
                            throw new BusException(ajaxr.Msg);
                        }
                        //查询仓库内成品物料信息
                        List<IT_LocalDetail> LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.MaterialId == jobdata.MaterialId && x.LocalId == locaId && x.PackId == "").ToListAsync();
                        PB_PickUpList pickupdata = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupQrCode && x.MaterialId == jobdata.MaterialId).FirstOrDefaultAsync();
                        PB_Location locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == locaId).FirstOrDefaultAsync();
                        double? Nums_N = 0;
                        double? Nums_O = 0;
                        double? dnums = data.Nums;
                        foreach (var item in LocalDetail)
                        {
                            if (dnums != 0)
                            {
                                if (item.Num == dnums)
                                {
                                    sqlMain += @" delete from IT_LocalDetail where Id='" + item.Id + "'; ";
                                    if (item.OldOrNew == 0)
                                    {
                                        Nums_O += item.Num;
                                    }
                                    else if (item.OldOrNew == 1)
                                    {
                                        Nums_N += item.Num;
                                    }
                                    dnums -= item.Num;
                                }
                                else if (item.Num > dnums)
                                {
                                    sqlMain += @" update IT_LocalDetail set Num=IFNULL(Num,0)-" + dnums + " where Id='" + item.Id + "'; ";
                                    if (item.OldOrNew == 0)
                                    {
                                        Nums_O += dnums;
                                    }
                                    else if (item.OldOrNew == 1)
                                    {
                                        Nums_N += dnums;
                                    }
                                    dnums -= dnums;
                                }
                                else if (item.Num < dnums)
                                {
                                    sqlMain += @" delete from IT_LocalDetail where Id='" + item.Id + "'; ";
                                    if (item.OldOrNew == 0)
                                    {
                                        Nums_O += item.Num;
                                    }
                                    else if (item.OldOrNew == 1)
                                    {
                                        Nums_N += item.Num;
                                    }
                                    dnums -= item.Num;
                                }
                            }
                            else
                            {
                                continue;
                            }
                        }
                        sqlMain += @" update IT_LocalMaterial set Nums_O=IFNULL(Nums_O,0)-" + Nums_O + ",Nums_N=IFNULL(Nums_N,0)-" + Nums_N + ",ScanNum=IFNULL(ScanNum,0)-" + (Nums_N + Nums_O) + " where  LocalId='" + locaId + "' and MaterialId='" + jobdata.MaterialId + "'; ";
                        IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == jobdata.MaterialId && x.LocalId == pickupdata.LocationId).FirstOrDefaultAsync();
                        if (LocalMaterial != null)
                        {
                            if (LocalMaterial.Nums_R > 1)
                            {
                                //减去备货单物料对应货位的占用量
                                sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-1 where  LocalId='" + pickupdata.LocationId + "' and MaterialId='" + jobdata.MaterialId + "';";
                            }
                            else
                            {
                                //减去备货单物料对应货位的占用量
                                sqlMain += @" update IT_LocalMaterial set Nums_R=0 where  LocalId='" + pickupdata.LocationId + "' and MaterialId='" + jobdata.MaterialId + "';";
                            }
                        }

                        //增加备货单明细日志
                        PB_UnLoadList pbdata = new PB_UnLoadList();
                        pbdata.Id = IdHelper.GetId();
                        pbdata.ParentId = pickupdata.Id;
                        pbdata.LocalId = locaId;
                        pbdata.PackId = "";
                        pbdata.MaterialId = jobdata.MaterialId;
                        pbdata.Nums = data.Nums;
                        pbdata.CreatorId = _operator.UserId;
                        pbdata.CreatorRealName = bdata.RealName;
                        pbdata.CreateTime = DateTime.Now;
                        pbdata.Deleted = false;
                        pbdata.JobId = "";
                        pbdata.OutNum = outnum;
                        UnLoadList.Add(pbdata);
                        //增加出库日志
                        PB_StockLog pblog = new PB_StockLog();
                        pblog.Id = IdHelper.GetId();
                        pblog.PackId = "";
                        pblog.MaterialId = jobdata.MaterialId;
                        pblog.StorId = locadata.StorId;
                        pblog.LocationId = locaId;
                        pblog.StockNumber = data.Nums;
                        pblog.CreatorId = _operator.UserId;
                        pblog.CreatorName = bdata.RealName;
                        pblog.OperatorId = _operator.UserId;
                        pblog.Type = 1;
                        pblog.OrderID = stockupQrCode;
                        pblog.CreateTime = DateTime.Now;
                        pblog.State = 1;
                        pblog.JobId = "";
                        StockLogList.Add(pblog);
                        sqlMain += @" update PB_PickUpList set ReadyNums=IFNULL(ReadyNums,0)+" + data.Nums + " where Id='" + pickupdata.Id + "'; ";
                    }
                }

                await Db.InsertAsync<PB_UnLoadList>(UnLoadList);

                await Db.InsertAsync<PB_StockLog>(StockLogList);

                await Db.InsertAsync<PB_UnpackingDetail>(UnpackingDetailList);

                await Db.InsertAsync<PB_Unpacking>(UnpackingList);

                await ExecuteSqlAsync(sqlMain);
            }
            catch (Exception ex)
            {
                throw new BusException(ajaxr.Msg);
            }
           
        }

        /// <summary>
        /// 下架出库复核
        /// </summary>
        /// <param name="stockupId">备货单Id</param>
        /// 增加项目备货记录  2022-03-04   赵锦涛
        /// 修改出库明细汇总物料ID   2022-03-06   赵锦涛
        /// <returns></returns>
        [Transactional]
        public async Task SubmitStockUpDataAsync(string stockupId)
        {
            string stockupid = stockupId;
            //var stockupData = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupQrCode.Split(',')[1].ToString()).ToListAsync();

            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            Expression<Func<PB_PickUpList, PB_Material, PB_PickUpListPriceDTO>> packselect = (a, b) => new PB_PickUpListPriceDTO
            {
                Price = b.Price
            };
            packselect = packselect.BuildExtendSelectExpre();
            var packdata = from a in Db.GetIQueryable<PB_PickUpList>().AsExpandable()
                           join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                           from b in ab.DefaultIfEmpty()
                           select @packselect.Invoke(a, b);
            var stockupData = packdata.Where(x => x.ParentId == stockupid).ToList();
            List<string> listdata = new List<string>();
            string sqlMain = "";
            int indexstate = 0;
            foreach (var item in stockupData)
            {
                if (item.ReadyNums == item.StockVolume)
                {
                    sqlMain += $@" update PB_PickUpList set State=1 where Id='" + item.Id + "'; ";
                    if (indexstate != 2 || indexstate == 0)
                    {
                        indexstate = 1;
                    }
                }
                else
                {
                    sqlMain += $@" update PB_PickUpList set State=2 where Id='" + item.Id + "'; ";
                    indexstate = 2;
                    double? itenums = 0;
                    itenums = item.StockVolume - (item.ReadyNums == null ? 0 : item.ReadyNums);
                    IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == item.MaterialId && x.LocalId == item.LocationId).FirstOrDefaultAsync();
                    if (LocalMaterial != null)
                    {
                        if (LocalMaterial.Nums_R < itenums)
                        {
                            itenums = 0;
                        }
                        sqlMain += @"  update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + itenums + " where MaterialId='" + item.MaterialId + "' and LocalId='" + item.LocationId + "'; ";
                    }
                }
            }


            //定义备货单状态
            int status = 0;
            //if (indexstate == 1)
            //{
            status = 3;
            double dbnum = 0;
            string outid = IdHelper.GetId();
            List<TD_OutStorDetail> listdetaildata = new List<TD_OutStorDetail>();
            int i = 0;
            string StorId = string.Empty;
            string AreaId = string.Empty;
            string RackId = string.Empty;
            foreach (var item in stockupData)
            {
                if (i == 0)
                {
                    var locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == item.LocationId).FirstOrDefaultAsync();
                    StorId = locadata.StorId;
                    AreaId = locadata.AreaId;
                    RackId = locadata.RackId;
                }
                TD_OutStorDetail outdetaildata = new TD_OutStorDetail();
                outdetaildata.Id = IdHelper.GetId();
                outdetaildata.StorId = StorId;
                outdetaildata.OutStorId = outid;
                outdetaildata.LocalId = item.LocationId;
                outdetaildata.AreaId = AreaId;
                outdetaildata.RackId = RackId;
                outdetaildata.MaterialId = item.MaterialId;
                outdetaildata.OutNum = Convert.ToDouble(item.ReadyNums);
                outdetaildata.Price = Convert.ToDouble(item.Price);
                outdetaildata.TotalAmt = Convert.ToDouble(item.ReadyNums) * Convert.ToDouble(item.Price);
                dbnum += Convert.ToDouble(item.ReadyNums);
                outdetaildata.CreatorId = _operator.UserId;
                outdetaildata.CreateTime = DateTime.Now;
                outdetaildata.Deleted = false;
                listdetaildata.Add(outdetaildata);
                i++;
            }
            if (dbnum == 0)
            {
                throw new BusException("出库数量为0不能提交");
            }


            //添加出库明细表
            List<TD_OutStorRecord> listtrecorddata = new List<TD_OutStorRecord>();
            var listd = listdetaildata.GroupBy(x => new { x.StorId, x.LocalId, x.OutStorId, x.MaterialId, x.Price }).Select(x => new { StorId = x.Key.StorId, LocalId = x.Key.LocalId, OutStorId = x.Key.OutStorId, MaterialId = x.Key.MaterialId, Price = x.Key.Price, Nums = x.Sum(n => n.OutNum) });
            foreach (var item in listd)
            {
                TD_OutStorRecord recodata = new TD_OutStorRecord();
                recodata.Id = IdHelper.GetId();
                recodata.StorId = item.StorId;
                recodata.OutStorId = item.OutStorId;
                recodata.MaterialId = item.MaterialId;
                recodata.OutNum = item.Nums;
                recodata.Price = item.Price;
                recodata.TotalAmt = item.Nums * item.Price;
                recodata.CreateTime = DateTime.Now;
                recodata.CreatorId = _operator.UserId;
                recodata.Deleted = false;
                listtrecorddata.Add(recodata);
            }


            //根据备货单获取项目Id和设计清单Id
            Expression<Func<PB_PickUpMain, PB_DeliveryNoticeItem, PB_DesignList, PickUpMainProjectDTO>> select = (a, b, c) => new PickUpMainProjectDTO
            {
                ProjectId = c.ProjectId,
                DesignId = b.DesignId
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_PickUpMain>().AsExpandable()
                    join b in Db.GetIQueryable<PB_DeliveryNoticeItem>() on a.ParentId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_DesignList>() on b.DesignId equals c.Id into bc
                    from c in bc.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            var PickUpMainProjectdata = await q.Where(x => x.Id == stockupid).FirstOrDefaultAsync();

            //创建出库单
            TD_OutStorage outdata = new TD_OutStorage();
            outdata.Id = outid;
            outdata.Code = GetTimeStamp();
            outdata.OutTime = DateTime.Now;
            outdata.StorageId = StorId;
            outdata.OutType = "Stockup";
            outdata.RefCode = stockupid;
            outdata.ProjectId = PickUpMainProjectdata.ProjectId;
            outdata.DesignId = PickUpMainProjectdata.DesignId;
            outdata.OutNum = dbnum;
            outdata.Status = 0;
            outdata.CreatorId = _operator.UserId;
            outdata.CreateTime = DateTime.Now;
            outdata.Deleted = false;
            outdata.QrCode = h_OutStorage + "," + outid;
            outdata.DepId = userdata.FactoryId;
            outdata.FactoryId = userdata.FactoryId;


            //}
            //else if (indexstate == 2)
            //{
            //    status = 2;
            //}


            //查询库存占用量是否满足
            //Expression<Func<PB_PickUpList, IT_LocalMaterial, PickListLocaMaterialDTO>> pickselect = (a, b) => new PickListLocaMaterialDTO
            //{
            //    PickMainId = a.ParentId,
            //    MaterialId = a.MaterialId,
            //    LocalId = a.LocationId,
            //    StockVolume = a.StockVolume,
            //    Nums_R = b.Nums_R == null ? 0 : b.Nums_R,
            //    SurplusNums = (b.Nums_R == null ? 0 : b.Nums_R) - a.StockVolume
            //};
            //pickselect = pickselect.BuildExtendSelectExpre();
            //var pickq = from a in Db.GetIQueryable<PB_PickUpList>().AsExpandable()
            //            join b in Db.GetIQueryable<IT_LocalMaterial>() on new { MaterialId = a.MaterialId, LocalId = a.LocationId } equals new { MaterialId = b.MaterialId, LocalId = b.LocalId } into ab
            //            from b in ab.DefaultIfEmpty()
            //            select @pickselect.Invoke(a, b);
            //var picklist = await pickq.Where(x => x.PickMainId == stockupid).ToListAsync();
            //var GreaterThanZero = picklist.Where(x => x.SurplusNums < 0).ToList();
            //if (GreaterThanZero.Count > 0)
            //{
            //    throw new BusException("请核实此货位的系统库存数量");
            //}

            ////更新库存占用量
            //var listdetdata = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupid).ToListAsync();
            //foreach (var item in listdetdata)
            //{
            //    sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + item.StockVolume + " where MaterialId='" + item.MaterialId + "' and LocalId='" + item.LocationId + "'; ";
            //}

            //修改备货单状态
            sqlMain += @" update PB_PickUpMain set Status=" + status + ",ToReviewId='" + _operator.UserId + "',ToReviewTime=NOW()  where id='" + stockupid + "'; ";

            //获取备货单对应的项目名称和楼号信息
            Expression<Func<PB_PickUpMain, PB_Project, PB_Buildingnumber, PB_PickUpMainProjectDataDTO>> projectselect = (a, b, c) => new PB_PickUpMainProjectDataDTO
            {
                ProjectName = b.Name,
                Buildingnumber = c.Buildingnumber
            };
            projectselect = projectselect.BuildExtendSelectExpre();
            var projectq = from a in Db.GetIQueryable<PB_PickUpMain>().AsExpandable()
                           join b in Db.GetIQueryable<PB_Project>() on a.ProjectId equals b.Id into ab
                           from b in ab.DefaultIfEmpty()
                           join c in Db.GetIQueryable<PB_Buildingnumber>() on a.BuildingNum equals c.Id into ac
                           from c in ac.DefaultIfEmpty()
                           select @projectselect.Invoke(a, b, c);
            var projectdata = await projectq.Where(x => x.Id == stockupid).FirstOrDefaultAsync();
            //添加项目备货记录
            PB_ProjectProcess prdata = new PB_ProjectProcess();
            prdata.Id = IdHelper.GetId();
            prdata.ProjectId = projectdata.ProjectId;
            prdata.ProjectName = projectdata.ProjectName;
            prdata.BuildingnumberId = projectdata.BuildingNum;
            prdata.BuildingnumberName = projectdata.Buildingnumber;
            prdata.ProcessType = "StockUp";
            prdata.OrderId = stockupid;
            prdata.Remarks = dbnum.ToString() + "件";
            prdata.CreatorId = _operator.UserId;
            prdata.CreatorRealName = userdata.RealName;
            prdata.CreateTime = DateTime.Now;
            prdata.Deleted = false;
            prdata.OrderId = stockupid;
            await Db.InsertAsync<PB_ProjectProcess>(prdata);

            await Db.InsertAsync<TD_OutStorDetail>(listdetaildata);

            await Db.InsertAsync<TD_OutStorRecord>(listtrecorddata);

            await Db.InsertAsync<TD_OutStorage>(outdata);

            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 下架出库提交
        /// </summary>
        /// <param name="stockupQrCode">备货单二维码</param>
        /// <returns></returns>
        public async Task SubmitStockUpToReviewAsync(string stockupQrCode)
        {
            string stockupid = stockupQrCode.Split(',')?[1].ToString();
            List<PB_PickUpList> PickUpList = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupid).ToListAsync();
            //获取备货单明细Id集合
            List<string> pickids = PickUpList.Select(x => x.Id).ToList();
            int ToReviewStatus = 0;
            foreach (var item in PickUpList)
            {
                if (item.ReadyNums != item.StockVolume)
                {
                    ToReviewStatus = 1;
                }
            }

            List<TD_OutStorage> tD_OutStorages = await Db.GetIQueryable<TD_OutStorage>().Where(x => x.RefCode == stockupid).ToListAsync();
            int outstoragesnum = tD_OutStorages.Count + 1;

            Base_LinkType link = await Db.GetIQueryable<Base_LinkType>().Where(x => x.LinkType == "OutStorage").FirstOrDefaultAsync();
            if (link.Whether == false)
            {
                Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

                //Expression<Func<PB_PickUpList, PB_Material, PB_PickUpListPriceDTO>> packselect = (a, b) => new PB_PickUpListPriceDTO
                //{
                //    Price = b.Price
                //};
                //packselect = packselect.BuildExtendSelectExpre();
                //var packdata = from a in Db.GetIQueryable<PB_PickUpList>().AsExpandable()
                //               join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                //               from b in ab.DefaultIfEmpty()
                //               select @packselect.Invoke(a, b);
                //var stockupData = packdata.Where(x => x.ParentId == stockupid).ToList();
                List<string> listdata = new List<string>();
                string sqlMain = "";
                int indexstate = 0;
                foreach (var item in PickUpList)
                {
                    if (item.ReadyNums == item.StockVolume)
                    {
                        sqlMain += $@" update PB_PickUpList set State=1 where Id='" + item.Id + "'; ";
                        if (indexstate != 2 || indexstate == 0)
                        {
                            indexstate = 1;
                        }
                    }
                    else
                    {
                        sqlMain += $@" update PB_PickUpList set State=2 where Id='" + item.Id + "'; ";
                        indexstate = 2;
                        //double? itenums = 0;
                        //itenums = item.StockVolume - (item.ReadyNums == null ? 0 : item.ReadyNums);
                        //IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.MaterialId == item.MaterialId && x.LocalId == item.LocationId).FirstOrDefaultAsync();
                        //if (LocalMaterial != null)
                        //{
                        //    if (LocalMaterial.Nums_R < itenums)
                        //    {
                        //        itenums = 0;
                        //    }
                        //    sqlMain += @"  update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + itenums + " where MaterialId='" + item.MaterialId + "' and LocalId='" + item.LocationId + "'; ";
                        //}
                    }
                }

                //查询最新备货出库的物料信息
                Expression<Func<PB_UnLoadList, PB_Material, PB_Location, UnLoadListDetaialDTO>> detaialselect = (a, b, c) => new UnLoadListDetaialDTO
                {
                    Price = b.Price,
                    AreaId = c.AreaId,
                    RackId = c.RackId,
                    StorId = c.StorId
                };
                detaialselect = detaialselect.BuildExtendSelectExpre();
                var detaialdata = from a in Db.GetIQueryable<PB_UnLoadList>().AsExpandable()
                                  join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                                  from b in ab.DefaultIfEmpty()
                                  join c in Db.GetIQueryable<PB_Location>() on a.LocalId equals c.Id into ac
                                  from c in ac.DefaultIfEmpty()
                                  select @detaialselect.Invoke(a, b, c);
                List<UnLoadListDetaialDTO> unLoadListDetaialDTOs = await detaialdata.Where(x => pickids.Contains(x.ParentId) && x.OutNum == outstoragesnum).ToListAsync();
                var detaiallist = unLoadListDetaialDTOs.GroupBy(x => new { x.LocalId, x.AreaId, x.RackId, x.StorId, x.MaterialId, x.Price }).Select(x => new { LocationId = x.Key.LocalId, AreaId = x.Key.AreaId, RackId = x.Key.RackId, StorId = x.Key.StorId, MaterialId = x.Key.MaterialId, Price = x.Key.Price, ReadyNums = x.Sum(m => m.Nums) }).ToList();

                //定义备货单状态
                int status = 0;
                //if (indexstate == 1)
                //{
                status = 3;
                double dbnum = 0;
                string outid = IdHelper.GetId();
                List<TD_OutStorDetail> listdetaildata = new List<TD_OutStorDetail>();
                //生成入库单创建台账数据
                //List<IT_RecordBook> iT_RecordBooks = new List<IT_RecordBook>(); 
                int i = 0;
                string StorId = string.Empty;
                string AreaId = string.Empty;
                string RackId = string.Empty;
                foreach (var item in detaiallist)
                {
                    //if (i == 0)
                    //{
                    //    var locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == item.LocationId).FirstOrDefaultAsync();
                    //    StorId = locadata.StorId;
                    //    AreaId = locadata.AreaId;
                    //    RackId = locadata.RackId;
                    //}
                    TD_OutStorDetail outdetaildata = new TD_OutStorDetail();
                    outdetaildata.Id = IdHelper.GetId();
                    outdetaildata.StorId = StorId;
                    outdetaildata.OutStorId = outid;
                    outdetaildata.LocalId = item.LocationId;
                    outdetaildata.AreaId = AreaId;
                    outdetaildata.RackId = RackId;
                    outdetaildata.MaterialId = item.MaterialId;
                    outdetaildata.OutNum = Convert.ToDouble(item.ReadyNums);
                    outdetaildata.Price = Convert.ToDouble(item.Price);
                    outdetaildata.TotalAmt = Convert.ToDouble(item.ReadyNums) * Convert.ToDouble(item.Price);
                    dbnum += Convert.ToDouble(item.ReadyNums);
                    outdetaildata.CreatorId = _operator.UserId;
                    outdetaildata.CreateTime = DateTime.Now;
                    outdetaildata.Deleted = false;
                    listdetaildata.Add(outdetaildata);
                    //创建台账model
                    //IT_RecordBook iT_RecordBook = new IT_RecordBook();
                    //iT_RecordBook.Id = IdHelper.GetId();
                    //iT_RecordBook.RefCode = outid;
                    //iT_RecordBook.Type = "Out";
                    //iT_RecordBook.FromStorId = "";
                    //iT_RecordBook.FromLocalId = "";
                    //iT_RecordBook.ToStorId = StorId;
                    //iT_RecordBook.ToLocalId = item.LocationId;
                    //iT_RecordBook.MaterialId = item.MaterialId;
                    //iT_RecordBook.MeasureId = "";
                    //iT_RecordBook.BarCode = "";
                    //iT_RecordBook.BatchNo = "";//批次号0
                    //iT_RecordBook.Num = Convert.ToDouble(item.ReadyNums);
                    //iT_RecordBook.CreateTime = DateTime.Now;
                    //iT_RecordBook.CreatorId = _operator.UserId;
                    //iT_RecordBook.Deleted = false;
                    //iT_RecordBooks.Add(iT_RecordBook);
                    i++;

                }
                if (dbnum == 0)
                {
                    throw new BusException("出库数量为0不能提交");
                }


                //添加出库明细表
                List<TD_OutStorRecord> listtrecorddata = new List<TD_OutStorRecord>();
                var listd = listdetaildata.GroupBy(x => new { x.StorId, x.LocalId, x.OutStorId, x.MaterialId, x.Price }).Select(x => new { StorId = x.Key.StorId, LocalId = x.Key.LocalId, OutStorId = x.Key.OutStorId, MaterialId = x.Key.MaterialId, Price = x.Key.Price, Nums = x.Sum(n => n.OutNum) });
                foreach (var item in listd)
                {
                    TD_OutStorRecord recodata = new TD_OutStorRecord();
                    recodata.Id = IdHelper.GetId();
                    recodata.StorId = item.StorId;
                    recodata.OutStorId = item.OutStorId;
                    recodata.MaterialId = item.MaterialId;
                    recodata.OutNum = item.Nums;
                    recodata.Price = item.Price;
                    recodata.TotalAmt = item.Nums * item.Price;
                    recodata.CreateTime = DateTime.Now;
                    recodata.CreatorId = _operator.UserId;
                    recodata.Deleted = false;
                    listtrecorddata.Add(recodata);
                }


                //根据备货单获取项目Id和设计清单Id
                Expression<Func<PB_PickUpMain, PB_DeliveryNoticeItem, PB_DesignList, PickUpMainProjectDTO>> select = (a, b, c) => new PickUpMainProjectDTO
                {
                    ProjectId = c.ProjectId,
                    DesignId = b.DesignId
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_PickUpMain>().AsExpandable()
                        join b in Db.GetIQueryable<PB_DeliveryNoticeItem>() on a.ParentId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_DesignList>() on b.DesignId equals c.Id into bc
                        from c in bc.DefaultIfEmpty()
                        select @select.Invoke(a, b, c);
                var PickUpMainProjectdata = await q.Where(x => x.Id == stockupid).FirstOrDefaultAsync();

                //创建出库单
                TD_OutStorage outdata = new TD_OutStorage();
                outdata.Id = outid;
                outdata.Code = GetTimeStamp();
                outdata.OutTime = DateTime.Now;
                outdata.StorageId = StorId;
                outdata.OutType = "Stockup";
                outdata.RefCode = stockupid;
                outdata.ProjectId = PickUpMainProjectdata.ProjectId;
                outdata.DesignId = PickUpMainProjectdata.DesignId;
                outdata.OutNum = dbnum;
                outdata.Status = 0;
                outdata.CreatorId = _operator.UserId;
                outdata.CreateTime = DateTime.Now;
                outdata.Deleted = false;
                outdata.QrCode = h_OutStorage + "," + outid;
                outdata.DepId = userdata.FactoryId;
                outdata.FactoryId = userdata.FactoryId;

                //查询库存占用量是否满足
                //Expression<Func<PB_PickUpList, IT_LocalMaterial, PickListLocaMaterialDTO>> pickselect = (a, b) => new PickListLocaMaterialDTO
                //{
                //    PickMainId = a.ParentId,
                //    MaterialId = a.MaterialId,
                //    LocalId = a.LocationId,
                //    StockVolume = a.StockVolume,
                //    Nums_R = b.Nums_R == null ? 0 : b.Nums_R,
                //    SurplusNums = (b.Nums_R == null ? 0 : b.Nums_R) - a.StockVolume
                //};
                //pickselect = pickselect.BuildExtendSelectExpre();
                //var pickq = from a in Db.GetIQueryable<PB_PickUpList>().AsExpandable()
                //            join b in Db.GetIQueryable<IT_LocalMaterial>() on new { MaterialId = a.MaterialId, LocalId = a.LocationId } equals new { MaterialId = b.MaterialId, LocalId = b.LocalId } into ab
                //            from b in ab.DefaultIfEmpty()
                //            select @pickselect.Invoke(a, b);
                //var picklist = await pickq.Where(x => x.PickMainId == stockupid).ToListAsync();
                //var GreaterThanZero = picklist.Where(x => x.SurplusNums < 0).ToList();
                //if (GreaterThanZero.Count > 0)
                //{
                //    throw new BusException("请核实备货单物料货位的库存量");
                //}

                ////更新库存占用量
                //var listdetdata = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == stockupid).ToListAsync();
                //string sqlMains = string.Empty;
                //foreach (var item in listdetdata)
                //{
                //    sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + item.StockVolume + " where MaterialId='" + item.MaterialId + "' and LocalId='" + item.LocationId + "'; ";
                //}

                //2023-05-08调整,每一次备货提交生成出库单,PDA备货提交不更改备货单状态,PC端备货单列表增加备货单完成按钮
                //修改备货单状态
                sqlMain += @" update PB_PickUpMain set ToReviewId='" + _operator.UserId + "',ToReviewStatus='" + ToReviewStatus + "',ToReviewTime=NOW()  where id='" + stockupid + "'; ";

                //获取备货单对应的项目名称和楼号信息
                Expression<Func<PB_PickUpMain, PB_Project, PB_Buildingnumber, PB_PickUpMainProjectDataDTO>> projectselect = (a, b, c) => new PB_PickUpMainProjectDataDTO
                {
                    ProjectName = b.Name,
                    Buildingnumber = c.Buildingnumber
                };
                projectselect = projectselect.BuildExtendSelectExpre();
                var projectq = from a in Db.GetIQueryable<PB_PickUpMain>().AsExpandable()
                               join b in Db.GetIQueryable<PB_Project>() on a.ProjectId equals b.Id into ab
                               from b in ab.DefaultIfEmpty()
                               join c in Db.GetIQueryable<PB_Buildingnumber>() on a.BuildingNum equals c.Id into ac
                               from c in ac.DefaultIfEmpty()
                               select @projectselect.Invoke(a, b, c);
                var projectdata = await projectq.Where(x => x.Id == stockupid).FirstOrDefaultAsync();
                //添加项目备货记录
                PB_ProjectProcess prdata = new PB_ProjectProcess();
                prdata.Id = IdHelper.GetId();
                prdata.ProjectId = projectdata.ProjectId;
                prdata.ProjectName = projectdata.ProjectName;
                prdata.BuildingnumberId = projectdata.BuildingNum;
                prdata.BuildingnumberName = projectdata.Buildingnumber;
                prdata.ProcessType = "StockUp";
                prdata.OrderId = stockupid;
                prdata.Remarks = dbnum.ToString() + "件";
                prdata.CreatorId = _operator.UserId;
                prdata.CreatorRealName = userdata.RealName;
                prdata.CreateTime = DateTime.Now;
                prdata.Deleted = false;
                prdata.OrderId = stockupid;
                await Db.InsertAsync<PB_ProjectProcess>(prdata);

                await Db.InsertAsync<TD_OutStorDetail>(listdetaildata);
                //await Db.InsertAsync<IT_RecordBook>(iT_RecordBooks);
                await Db.InsertAsync<TD_OutStorRecord>(listtrecorddata);

                await Db.InsertAsync<TD_OutStorage>(outdata);

                await ExecuteSqlAsync(sqlMain);
            }
            else if (link.Whether == true)
            {
                ////修改备货单状态
                //string sqlstr = @"update PB_PickUpMain set Status=4,ToReviewStatus='" + ToReviewStatus + "' where id='" + stockupid + "'";
                //await ExecuteSqlAsync(sqlstr);
            }
        }

        /// <summary>
        /// 备货单提交返回未备物料信息
        /// </summary>
        /// <param name="stockupQrCode">备货单二维码</param>
        /// <returns></returns>
        public async Task<List<StockUpMaterialDTO>> GetStockUpMaterialListAsync(string stockupQrCode)
        {
            string stockupid = stockupQrCode.Split(',')?[1].ToString();
            string sqlMian = $@"select a.MaterialId,b.`Name` as MaterialName,b.`Code` as MaterialCode,b.Spec as MaterialSpec,(a.StockVolume-a.ReadyNums) as Nums from pb_pickuplist as a
left join pb_material as b on a.MaterialId=b.Id
where a.ParentId='{stockupid}' and (a.StockVolume-a.ReadyNums)>0";
            return await Db.GetListBySqlAsync<StockUpMaterialDTO>(sqlMian);
        }

        /// <summary>
        /// 取消备货单提交
        /// </summary>
        /// <param name="stockupQrCode">备货单二维码</param>
        /// 增加取消备货单提交功能   2022-02-20   赵锦涛
        /// <returns></returns>
        [Transactional]
        public async Task CancelStockUpAsync(string stockupQrCode)
        {
            //备货单Id
            string pickmainId = stockupQrCode.Split(',')?[1].ToString();
            string sqlstr = string.Empty;
            //修改备货单状态为开始作业
            sqlstr += @" update PB_PickUpMain set Status=2,ToReviewStatus=NULL,ToReviewId=NULL,ToReviewTime=NULL where Id='" + pickmainId + "'; ";

            TD_OutStorage outdata = await Db.GetIQueryable<TD_OutStorage>().Where(x => x.RefCode == pickmainId).FirstOrDefaultAsync();
            if (outdata != null)
            {
                //删除出库单
                sqlstr += @" delete from TD_OutStorRecord where OutStorId='" + outdata.Id + "'; ";
                sqlstr += @" delete from TD_OutStorDetail where OutStorId='" + outdata.Id + "'; ";
                sqlstr += @" delete from TD_OutStorage where Id='" + outdata.Id + "'; ";
                //删除台账数据
                sqlstr += @" delete from IT_RecordBook where RefCode='" + outdata.Id + "'; ";

                //查询备货单明细
                List<PB_PickUpList> PickUpList = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == pickmainId).ToListAsync();
                foreach (var item in PickUpList)
                {
                    double? dnums = item.StockVolume - item.ReadyNums;
                    sqlstr += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)+" + dnums + " where MaterialId='" + item.MaterialId + "' and LocalId='" + item.LocationId + "'; ";
                }
                //项目备货记录
                sqlstr += @" delete from PB_ProjectProcess where OrderId='" + pickmainId + "'; ";
            }
            //删除对应的出货单
            await ExecuteSqlAsync(sqlstr);
        }

        /// <summary>
        /// 判断下架出库的包对应货位的项目是否与备货单对应的项目一致
        /// </summary>
        /// <param name="packqrcode">包二维码</param>
        /// <param name="stockupQrCode">备货单二维码</param>
        /// <returns></returns>
        public async Task<bool> GetLocationProjectTruOrFalseAsync(string packqrcode, string stockupQrCode)
        {
            bool bl = true;
            //包Id
            //包编号/物料编号
            string packId = string.Empty;
            string materialId = string.Empty;
            string packmodel = packqrcode.Split(',')?[0].ToString();
            if (packmodel == "13")
            {
                packId = packqrcode.Split(',')?[1].ToString();
            }
            else if (packmodel == "04")
            {
                var model = packqrcode.Split(',');
                if (model.Length > 2)
                {
                    materialId = model?[3].ToString();
                }
                else
                {
                    materialId = model?[1].ToString();
                }
            }
            //备货单Id
            string pickupId = stockupQrCode.Split(',')?[1].ToString();
            //查询备货单信息
            Expression<Func<PB_PickUpMain, PB_DeliveryNoticeItem, PB_DeliveryNotice, PB_PickUpListProjectDTO>> pickselect = (a, b, c) => new PB_PickUpListProjectDTO
            {
                ProjectId = c.ProjectId
            };
            pickselect = pickselect.BuildExtendSelectExpre();
            var pickq = from a in Db.GetIQueryable<PB_PickUpMain>().AsExpandable()
                        join b in Db.GetIQueryable<PB_DeliveryNoticeItem>() on a.ParentId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_DeliveryNotice>() on b.ParentId equals c.Id into bc
                        from c in bc.DefaultIfEmpty()
                        select @pickselect.Invoke(a, b, c);
            var pickdata = await pickq.Where(x => x.Id == pickupId).FirstOrDefaultAsync();
            if (packmodel == "13")
            {
                //查询包在仓库对应的货位的信息
                Expression<Func<PB_Location, IT_LocalDetail, PB_LocationProjectDTO>> select = (a, b) => new PB_LocationProjectDTO
                {
                    PackId = b.PackId
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_Location>().AsExpandable()
                        join b in Db.GetIQueryable<IT_LocalDetail>() on a.Id equals b.LocalId into ab
                        from b in ab.DefaultIfEmpty()
                        select @select.Invoke(a, b);
                var locadata = await q.Where(x => x.PackId == packId).FirstOrDefaultAsync();

                if (locadata != null)
                {
                    //货位是否有项目信息
                    if (locadata.ProjectId.IsNullOrEmpty())
                    {
                        bl = true;
                    }
                    else
                    {
                        if (locadata.ProjectId == pickdata.ProjectId)
                        {
                            bl = true;
                        }
                        else
                        {
                            bl = false;
                        }
                    }
                }
            }
            else
            {
                PB_PickUpList pbdata = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == pickupId && x.MaterialId == materialId).FirstOrDefaultAsync();
                if (pbdata != null)
                {
                    PB_Location locadata = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == pbdata.LocationId).FirstOrDefaultAsync();
                    if (locadata != null)
                    {
                        //货位是否有项目信息
                        if (locadata.ProjectId.IsNullOrEmpty())
                        {
                            bl = true;
                        }
                        else
                        {
                            if (locadata.ProjectId == pickdata.ProjectId)
                            {
                                bl = true;
                            }
                            else
                            {
                                bl = false;
                            }
                        }
                    }
                }
            }
            return bl;
        }

        /// <summary>
        /// 出库扫描单个物料
        /// </summary>
        /// <param name="packqrcode">物料二维码</param>
        /// <param name="stockupQrCode">备货单二维码</param>
        /// <param name="locaQrcode">货位二维码</param>
        /// <returns></returns>
        public async Task<PB_PickUpListDataDTO> GetMaterialDataAsync(string packqrcode, string stockupQrCode, string locaQrcode)
        {
            string localId = locaQrcode.Split(',')?[1].ToString();
            string pickid = stockupQrCode.Split(',')?[1].ToString();
            var packmodel = packqrcode.Split(',')?[0];
            string packid = string.Empty;
            if (packmodel == "04")
            {
                var model = packqrcode.Split(',');
                if (model.Length > 2)
                {
                    if (model.Length < 4)
                    {
                        throw new BusException("请扫描或输入正确的物料二维码");
                    }
                    else
                    {
                        packid = model?[3].ToString();
                    }
                }
                else
                {
                    packid = model?[1].ToString();
                }
            }
            //合并重复物料指向新的物料Id
            PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == packid).FirstOrDefaultAsync();
            if (materdata == null)
            {
                throw new BusException("请扫描或输入正确的物料二维码");
            }
            if (!materdata.TransferId.IsNullOrEmpty())
            {
                packid = materdata.TransferId;
            }
            Expression<Func<PB_Material, PB_PickUpList, PB_PickUpListDataDTO>> select = (a, b) => new PB_PickUpListDataDTO
            {
                Id = a.Id,
                Code = a.Code,
                Name = a.Name,
                Spec = a.Spec,
                Nums = b.StockVolume - (b.ReadyNums == null ? 0 : b.ReadyNums),
                PickId = b.ParentId,
                LocalId = b.LocationId
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_Material>().AsExpandable()
                    join b in Db.GetIQueryable<PB_PickUpList>() on a.Id equals b.MaterialId into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            var res = await q.Where(x => x.Id == packid && x.PickId == pickid && x.LocalId == localId).FirstOrDefaultAsync();
            if (res.IsNullOrEmpty())
            {
                throw new BusException("请检查物料与备货单物料是否匹配");
            }
            return res;
        }

        /// <summary>
        /// 初始化出库单表数据
        /// 只作用2022-03更新生产库使用
        /// </summary>
        /// <returns></returns>
        [Transactional]
        public async Task ResetStockUpDataAsync()
        {

            Expression<Func<PB_PickUpList, PB_Material, PB_UnLoadList, PB_Location, PB_PickUpMain, PB_DeliveryNoticeItem, Base_User, ResetOutStorageDTO>> select = (a, b, c, d, e, f, g) => new ResetOutStorageDTO
            {
                Price = b.Price,
                StorId = d.StorId,
                //LocalId = c.LocalId,
                AreaIds = d.AreaId,
                RackIds = d.RackId,
                Nums = c.Nums,
                MainId = e.Id,
                ProjectId = e.ProjectId,
                DesignId = f.DesignId,
                Status = e.Status,
                detpId = g.DepartmentId,
                FactoryId = g.FactoryId,
                Createdate = e.CreateTime.ToString("yyyy-MM-dd")
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_PickUpList>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_UnLoadList>() on a.Id equals c.ParentId into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_Location>() on a.LocationId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<PB_PickUpMain>() on a.ParentId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_DeliveryNoticeItem>() on e.ParentId equals f.Id into ef
                    from f in ef.DefaultIfEmpty()
                    join g in Db.GetIQueryable<Base_User>() on e.CreatorId equals g.Id into eg
                    from g in eg.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e, f, g);
            var undata = await q.Where(x => x.Status == 3).ToListAsync();
            List<TD_OutStorage> storage = new List<TD_OutStorage>();
            List<TD_OutStorDetail> detail = new List<TD_OutStorDetail>();
            List<TD_OutStorRecord> Record = new List<TD_OutStorRecord>();

            //获取备货单信息
            var storagelist = undata.GroupBy(x => new { x.MainId, x.ProjectId, x.DesignId, x.detpId, x.FactoryId, x.CreatorId, x.Createdate }).Select(x => new { MainId = x.Key.MainId, ProjectId = x.Key.ProjectId, DesignId = x.Key.DesignId, detpId = x.Key.detpId, FactoryId = x.Key.FactoryId, CreatorId = x.Key.CreatorId, Createdate = x.Key.Createdate }).ToList();

            //获取备货单明细信息
            var storagedetail = undata.GroupBy(x => new { x.Id, x.MainId, x.LocationId, x.AreaIds, x.RackIds, x.Price, x.MaterialId, x.ReadyNums, x.CreatorId, x.CreateTime }).Select(x => new
            {
                Id = x.Key.Id,
                MainId = x.Key.MainId,
                LocationId = x.Key.LocationId,
                AreaIds = x.Key.AreaIds,
                RackIds = x.Key.RackIds,
                Price = x.Key.Price,
                MaterialId = x.Key.MaterialId,
                ReadyNums = x.Key.ReadyNums,
                CreatorId = x.Key.CreatorId,
                CreateTime = x.Key.CreateTime.ToString("yyyy-MM-dd"),
            }).ToList();

            //获取备货单物料明细汇总
            var materdata = undata.GroupBy(x => new { x.Id, x.MainId, x.Price, x.MaterialId, x.ReadyNums, x.CreatorId, x.CreateTime }).Select(x => new
            {
                Id = x.Key.Id,
                MainId = x.Key.MainId,
                Price = x.Key.Price,
                MaterialId = x.Key.MaterialId,
                ReadyNums = x.Key.ReadyNums,
                CreatorId = x.Key.CreatorId,
                CreateTime = x.Key.CreateTime.ToString("yyyy-MM-dd")
            }).ToList();

            List<PB_DesignList> designlist = await Db.GetIQueryable<PB_DesignList>().ToListAsync();

            string StorId = "1480002827643260928";

            foreach (var item in storagelist)
            {
                string outid = IdHelper.GetId();
                //获取备货单的明细信息
                var undetail = storagedetail.Where(x => x.MainId == item.MainId).ToList();
                //获取物料在备货单的总数
                double dbnum = 0;
                foreach (var item2 in undetail)
                {
                    TD_OutStorDetail outdetaildata = new TD_OutStorDetail();
                    outdetaildata.Id = IdHelper.GetId();
                    outdetaildata.StorId = StorId;
                    outdetaildata.OutStorId = outid;
                    outdetaildata.LocalId = item2.LocationId;
                    outdetaildata.AreaId = item2.AreaIds;
                    outdetaildata.RackId = item2.RackIds;
                    outdetaildata.MaterialId = item2.MaterialId;
                    outdetaildata.OutNum = Convert.ToDouble(item2.ReadyNums);
                    outdetaildata.Price = Convert.ToDouble(item2.Price);
                    outdetaildata.TotalAmt = Convert.ToDouble(item2.ReadyNums) * Convert.ToDouble(item2.Price);
                    dbnum += Convert.ToDouble(item2.ReadyNums);
                    outdetaildata.CreatorId = item2.CreatorId;
                    outdetaildata.CreateTime = Convert.ToDateTime(item2.CreateTime);
                    outdetaildata.Deleted = false;
                    detail.Add(outdetaildata);
                }

                //获取物料汇总信息
                var materdatalist = materdata.Where(x => x.MainId == item.MainId).ToList();
                foreach (var item3 in materdatalist)
                {
                    TD_OutStorRecord recodata = new TD_OutStorRecord();
                    recodata.Id = IdHelper.GetId();
                    recodata.StorId = StorId;
                    recodata.OutStorId = outid;
                    recodata.MaterialId = item3.MaterialId;
                    recodata.OutNum = Convert.ToDouble(item3.ReadyNums);
                    recodata.Price = item3.Price;
                    recodata.TotalAmt = item3.ReadyNums * item3.Price;
                    recodata.CreateTime = Convert.ToDateTime(item3.CreateTime);
                    recodata.CreatorId = item3.CreatorId;
                    recodata.Deleted = false;
                    Record.Add(recodata);
                }

                //创建出库单
                TD_OutStorage outdata = new TD_OutStorage();
                outdata.Id = outid;
                outdata.Code = IdHelper.GetId();
                outdata.OutTime = Convert.ToDateTime(item.Createdate);
                outdata.StorageId = StorId;
                outdata.OutType = "Stockup";
                outdata.RefCode = item.MainId;
                outdata.ProjectId = item.ProjectId;
                outdata.DesignId = item.DesignId;
                outdata.OutNum = dbnum;
                outdata.CreatorId = item.CreatorId;
                outdata.CreateTime = Convert.ToDateTime(item.Createdate);
                outdata.Deleted = false;
                outdata.Status = 0;
                outdata.QrCode = h_OutStorage + "," + outid;
                outdata.DepId = item.detpId;
                outdata.FactoryId = item.FactoryId;
                storage.Add(outdata);

            }

            await Db.InsertAsync<TD_OutStorRecord>(Record);
            await Db.InsertAsync<TD_OutStorDetail>(detail);
            await Db.InsertAsync<TD_OutStorage>(storage);
        }

        /// <summary>
        /// 通过发货通知单明细获取发货计划明细信息
        /// </summary>
        /// <param name="ReserveParent">发货通知单明细id</param>
        /// <returns></returns>
        public async Task<PageResult<PB_DeliveryPlanDetailsDTO>> GetDeliveryPlanDetails(PageInput<ConditionDTO> input, string ReserveParent)
        {
            var q = await Db.GetIQueryable<PB_DeliveryNoticeItem>().Where(s => s.Id == ReserveParent).FirstOrDefaultAsync();
            var p = await Db.GetIQueryable<PB_DesignList>().Where(s => s.Id == q.DesignId).FirstOrDefaultAsync();
            Expression<Func<PB_DeliveryPlanDetails, PB_Project, PB_Buildingnumber, PB_DeliveryPlanDetailsDTO>> packselect = (a, b, c) => new PB_DeliveryPlanDetailsDTO
            {
                ProjectName = b.Name,
                BulidingName = c.Buildingnumber,
            };
            packselect = packselect.BuildExtendSelectExpre();
            var packdata = from a in Db.GetIQueryable<PB_DeliveryPlanDetails>().AsExpandable()
                           join b in Db.GetIQueryable<PB_Project>() on a.ProjectId equals b.Id into ab
                           from b in ab.DefaultIfEmpty()
                           join c in Db.GetIQueryable<PB_Buildingnumber>() on a.BuildingId equals c.Id into ac
                           from c in ac.DefaultIfEmpty()
                           select @packselect.Invoke(a, b, c);
            packdata = packdata.Where(x => x.ProjectId == p.ProjectId && x.BuildingId == p.BuildingNumberID);

            var PageData = await packdata.GetPageResultAsync(input);
            return PageData;
        }

        /// <summary>
        /// 对7月之前未扫码的备货单做数据处理,生成出库单,更改库存占用量,更改备货单的状态,在备货单Remarks字段增加备货单的备注
        /// </summary>
        /// <param name="PickMainId">备货单ID</param>
        /// <returns></returns>
        [Transactional]
        public async Task UpdateInventoryAsync(string PickMainId)
        {
            //DateTime dttime = Convert.ToDateTime("2022-07-01");
            //查询所有备货单明细信息
            Expression<Func<PB_PickUpList, PB_PickUpMain, PB_Material, PB_Location, Base_User, PB_DeliveryNoticeItem, PickUpListModelDTO>> select = (a, b, c, d, e, f) => new PickUpListModelDTO
            {
                DeliveryTime = b.CreateTime,
                Status = b.Status,
                Price = c.Price,
                Weight = c.Weight,
                StorId = d.StorId,
                DepId = e.DepartmentId,
                FactoryId = e.FactoryId,
                ProjectId = b.ProjectId,
                DesignId = f.DesignId
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_PickUpList>().AsExpandable()
                    join b in Db.GetIQueryable<PB_PickUpMain>() on a.ParentId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_Location>() on a.LocationId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<Base_User>() on a.CreatorId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_DeliveryNoticeItem>() on b.ParentId equals f.Id into bf
                    from f in bf.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e, f);
            List<PickUpListModelDTO> listdata = await q.Where(x => x.ParentId == PickMainId).ToListAsync();

            //定义出库单
            List<TD_OutStorage> OutStoragelist = new List<TD_OutStorage>();
            List<TD_OutStorDetail> OutStorDetaillist = new List<TD_OutStorDetail>();
            List<TD_OutStorRecord> OutStorRecordlist = new List<TD_OutStorRecord>();

            //根据备货单明细信息获取备货单信息
            var pickupmain = listdata.GroupBy(x => new { x.ParentId, x.StorId, x.DeliveryTime, x.CreatorId, x.DepId, x.FactoryId, x.ProjectId, x.DesignId }).Select(x => new { PickMainId = x.Key.ParentId, StorId = x.Key.StorId, DeliveryTime = x.Key.DeliveryTime, CreatorId = x.Key.CreatorId, DepId = x.Key.DepId, FactoryId = x.Key.FactoryId, ProjectId = x.Key.ProjectId, DesignId = x.Key.DesignId }).ToList();

            string sqlMain = string.Empty;
            //循环处理备货单生成出库单
            foreach (var item in pickupmain)
            {
                //生成出库单Id
                string OutId = IdHelper.GetId();

                //获取备货单的明细信息
                var itemdata = listdata.Where(x => x.ParentId == item.PickMainId).ToList();

                double? doutnum = 0;
                double? dTotalAmt = 0;

                int indexstate = 0;

                int ToReviewStatus = 0;

                foreach (var picklist in itemdata)
                {
                    TD_OutStorDetail osddata = new TD_OutStorDetail();
                    osddata.Id = IdHelper.GetId();
                    osddata.StorId = item.StorId;
                    osddata.OutStorId = OutId;
                    osddata.LocalId = picklist.LocationId;
                    osddata.MaterialId = picklist.MaterialId;
                    osddata.Price = Convert.ToDouble(picklist.Price);
                    osddata.TotalAmt = Convert.ToDouble(picklist.ReadyNums * picklist.Price);
                    osddata.OutNum = Convert.ToDouble(picklist.ReadyNums);
                    osddata.CreateTime = Convert.ToDateTime(item.DeliveryTime);
                    osddata.CreatorId = item.CreatorId;
                    osddata.Deleted = false;
                    osddata.OldOrNew = 1;
                    OutStorDetaillist.Add(osddata);

                    TD_OutStorRecord osrdata = new TD_OutStorRecord();
                    osrdata.Id = IdHelper.GetId();
                    osrdata.StorId = item.StorId;
                    osrdata.OutStorId = OutId;
                    osrdata.MaterialId = picklist.MaterialId;
                    osrdata.TotalAmt = Convert.ToDouble(picklist.ReadyNums * picklist.Price);
                    osrdata.OutNum = Convert.ToDouble(picklist.ReadyNums);
                    osrdata.CreateTime = Convert.ToDateTime(item.DeliveryTime);
                    osrdata.CreatorId = item.CreatorId;
                    osrdata.Deleted = false;
                    OutStorRecordlist.Add(osrdata);

                    sqlMain += @" update IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + picklist.StockVolume + " where LocalId='" + picklist.LocationId + "' and MaterialId='" + picklist.MaterialId + "'; ";

                    doutnum += Convert.ToDouble(picklist.ReadyNums);
                    dTotalAmt += Convert.ToDouble(picklist.ReadyNums * picklist.Price);

                    if (picklist.ReadyNums == picklist.StockVolume)
                    {
                        sqlMain += @" update PB_PickUpList set State=1 where Id='" + picklist.Id + "'; ";
                        if (indexstate != 2 || indexstate == 0)
                        {
                            indexstate = 1;
                        }
                    }
                    else
                    {
                        sqlMain += @" update PB_PickUpList set State=2 where Id='" + picklist.Id + "'; ";
                        indexstate = 2;
                        ToReviewStatus = 1;
                    }

                    sqlMain += @" update PB_PickUpMain set Status=3,ToReviewId='" + item.CreatorId + "',ToReviewStatus='" + ToReviewStatus + "',ToReviewTime=NOW()  where Id='" + item.PickMainId + "'; ";
                }

                TD_OutStorage osdata = new TD_OutStorage();
                osdata.Id = OutId;
                osdata.StorageId = item.StorId;
                osdata.Code = GetTimeStamp();
                osdata.OutTime = Convert.ToDateTime(item.DeliveryTime);
                osdata.OutType = "Stockup";
                osdata.RefCode = item.PickMainId;
                osdata.OutNum = doutnum;
                osdata.TotalAmt = dTotalAmt;
                osdata.Status = 0;
                osdata.CreateTime = item.DeliveryTime;
                osdata.CreatorId = item.CreatorId;
                osdata.Deleted = false;
                osdata.QrCode = h_OutStorage + "," + OutId;
                osdata.DepId = item.DepId;
                osdata.ProjectId = item.ProjectId;
                osdata.DesignId = item.DesignId;
                osdata.FactoryId = item.FactoryId;
                OutStoragelist.Add(osdata);
            }

            await Db.InsertAsync<TD_OutStorDetail>(OutStorDetaillist);
            await Db.InsertAsync<TD_OutStorRecord>(OutStorRecordlist);
            await Db.InsertAsync<TD_OutStorage>(OutStoragelist);
            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 分批步数备货提交
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<AjaxResult> AddStepsPickMain(AddStepsPickMain data)
        {
            AjaxResult falseReturn = new AjaxResult
            {
                Success = false,
                Msg = "失败请重新刷新库存！库存量不足"
            };
            //获取可用库存数据
            var LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().ToListAsync();
            if (data.SubData.Count > 0)
            {
                for (int i = 0; i < data.SubData?.Count; i++)
                {
                    for (int k = 0; k < data.SubData[i].childrenList.Count; k++)
                    {
                        var LocalMaterialInfo = LocalMaterial.Where(P => P.LocalId == data.SubData[i].childrenList[k].LocationId && P.MaterialId == data.SubData[i].childrenList[k].MaterialId).FirstOrDefault();
                        if (LocalMaterialInfo == null)
                        {
                            return falseReturn;
                        }
                        if ((LocalMaterialInfo.Nums_N + LocalMaterialInfo.Nums_O - LocalMaterialInfo.Nums_R) < data.SubData[i].childrenList[k].StockVolume)
                        {
                            return falseReturn;
                        }
                    }
                }
            }
            //创建备货单主表
            PB_PickUpMain pB_PickUpMain = new PB_PickUpMain();
            //创建备货与分布对应关系表
            List<PB_PickListSteps> pB_PickListSteplist = new List<PB_PickListSteps>();
            List<PB_PickUpList> pB_PickUpLists1 = new List<PB_PickUpList>();
            string id = IdHelper.GetId();
            pB_PickUpMain.Id = id;
            pB_PickUpMain.QrCode = "21," + id;
            pB_PickUpMain.CreateTime = DateTime.Now;
            pB_PickUpMain.CreatorId = _operator.UserId;
            pB_PickUpMain.Deleted = false;
            pB_PickUpMain.Memo = data.Memo;
            pB_PickUpMain.StyleName = data.StyleName;
            pB_PickUpMain.DeliveryTime = data.DeliveryTime;
            pB_PickUpMain.CusID = data.CusID;
            pB_PickUpMain.CusName = data.CusName;
            pB_PickUpMain.CustomerAddress = data.CustomerAddress;
            pB_PickUpMain.Toexamine = "待审核";
            pB_PickUpMain.Status = 0;
            pB_PickUpMain.BuildingId = data.BuildingId;
            pB_PickUpMain.ParentId = data.ParentId;
            pB_PickUpMain.BuildingNum = data.BuildingId;
            pB_PickUpMain.ProjectId = data.ProjectId;
            pB_PickUpMain.AssociatedDelivery = data.AssociatedDelivery;
            pB_PickUpMain.UpdateTime = DateTime.Now;
            await Db.InsertAsync<PB_PickUpMain>(pB_PickUpMain);
            string steptitle = "";
            string Updatesql = "";
            for (int steps = 0; steps < data.SubData.Count; steps++)
            {
                for (int items = 0; items < data.SubData[steps].childrenList.Count; items++)
                {
                    PB_PickListSteps pB_PickListSteps = new PB_PickListSteps();
                    string itemid = IdHelper.GetId();
                    pB_PickListSteps.Id = itemid;
                    pB_PickListSteps.ParentId = id;
                    pB_PickListSteps.AreaId = data.SubData[steps].childrenList[items].AreaId;
                    pB_PickListSteps.RackId = data.SubData[steps].childrenList[items].RackId;
                    pB_PickListSteps.LocationId = data.SubData[steps].childrenList[items].LocationId;
                    pB_PickListSteps.StockVolume = data.SubData[steps].childrenList[items].StockVolume;
                    pB_PickListSteps.ReadyNums = 0;
                    pB_PickListSteps.SubId = data.SubData[steps].childrenList[items].PB_DesignListInfo;
                    pB_PickListSteps.MaterialId = data.SubData[steps].childrenList[items].MaterialId;
                    pB_PickListSteps.Remarks = data.SubData[steps].childrenList[items].Remarks;
                    pB_PickListSteps.CreateTime = DateTime.Now;
                    pB_PickListSteps.CreatorId = _operator.UserId;
                    pB_PickListSteps.State = 0;
                    pB_PickListSteps.Deleted = false;
                    pB_PickListSteps.StepIndex = data.SubData[steps].key;
                    pB_PickListSteps.Slot = items;
                    if (!string.IsNullOrEmpty(data.SubData[steps].childrenList[items].StockVolume.ToString()))
                    {
                        Updatesql += "UPDATE IT_LocalMaterial SET Nums_R = IFNULL(Nums_R,0) +'" + data.SubData[steps].childrenList[items].StockVolume + "' WHERE LocalId='" + data.SubData[steps].childrenList[items].LocationId + "' AND MaterialId='" + data.SubData[steps].childrenList[items].MaterialId + "';";
                    }
                    pB_PickListSteplist.Add(pB_PickListSteps);
                    //设计清单拼装已备货数量
                    steptitle = data.SubData[steps].key + "Ready";
                    //反填设计清单已备数量
                    string sql = "update  PB_DesignDetail set " + steptitle + "= IFNULL(" + steptitle + ", 0)+" + data.SubData[steps].childrenList[items].StockVolume + " where MaterialId='" + data.SubData[steps].childrenList[items].MaterialId + "' AND Id='" + data.SubData[steps].childrenList[items].PB_DesignListInfo + "'";
                    await Db.ExecuteSqlAsync(sql);
                }
            }


            if (pB_PickListSteplist?.Count > 0)
            {
                await Db.InsertAsync(pB_PickListSteplist);
                //获取分步同group 获取同一货位的物料总和
                var PickListStepGroupList = pB_PickListSteplist.GroupBy(x => new { x.AreaId, x.RackId, x.LocationId, x.MaterialId, x.SubId }).Select(x => new { AreaId = x.Key.AreaId, RackId = x.Key.RackId, LocationId = x.Key.LocationId, MaterialId = x.Key.MaterialId, SubId = x.Key.SubId, StockVolume = x.Sum(n => n.StockVolume) });
                foreach (var item in PickListStepGroupList)
                {
                    //创建备货单
                    PB_PickUpList pB_PickUpList = new PB_PickUpList();
                    pB_PickUpList.Id = IdHelper.GetId();
                    pB_PickUpList.ParentId = id;
                    pB_PickUpList.AreaId = item.AreaId;
                    pB_PickUpList.RackId = item.RackId;
                    pB_PickUpList.MaterialId = item.MaterialId;
                    pB_PickUpList.LocationId = item.LocationId;
                    pB_PickUpList.StockVolume = item.StockVolume;
                    pB_PickUpList.ReadyNums = 0;
                    pB_PickUpList.SubId = item.SubId;
                    pB_PickUpList.State = 0;
                    pB_PickUpList.CreateTime = DateTime.Now;
                    var pb_d = await Db.GetIQueryable<PB_DesignDetail>().Where(m => m.Id == pB_PickUpList.SubId).FirstOrDefaultAsync();
                    if (pb_d != null)
                    {
                        pB_PickUpList.Remarks = pb_d.Remarks;
                    }
                    else
                    {
                        pB_PickUpList.Remarks = "";
                    }
                    pB_PickUpList.CreatorId = _operator.UserId;
                    pB_PickUpList.Deleted = false;
                    pB_PickUpList.ShippedNums = 0;
                    pB_PickUpList.OddNumber = "";
                    pB_PickUpList.ShippingId = "";
                    pB_PickUpLists1.Add(pB_PickUpList);

                }
                if (pB_PickUpLists1.Count > 0)
                {
                    await Db.InsertAsync(pB_PickUpLists1);
                }
            }
            if (!string.IsNullOrEmpty(Updatesql))
            {
                await ExecuteSqlAsync(Updatesql);
            }
            AjaxResult res = new AjaxResult
            {
                Success = true,
                Msg = "请求成功！"
            };

            return res;
        }
        /// <summary>
        /// 获取分布表格数据
        /// </summary>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        public async Task<AddStepsPickMain> GetStepPickMain(string ParentId, string ItemId)
        {
            var Pb_PiackMain = await Db.GetIQueryable<PB_PickUpMain>().Where(m => m.Id == ParentId).FirstOrDefaultAsync();
            AddStepsPickMain addStepsPickMain = new AddStepsPickMain();
            addStepsPickMain.Id = Pb_PiackMain.Id;
            addStepsPickMain.CreateTime = Pb_PiackMain.CreateTime;
            addStepsPickMain.Remarks = Pb_PiackMain.Remarks;
            addStepsPickMain.CreatorId = Pb_PiackMain.CreatorId;
            addStepsPickMain.Deleted = Pb_PiackMain.Deleted;
            addStepsPickMain.StyleName = Pb_PiackMain.StyleName;
            addStepsPickMain.DeliveryTime = Pb_PiackMain.DeliveryTime;
            addStepsPickMain.CusID = Pb_PiackMain.CusID;
            addStepsPickMain.CusID = Pb_PiackMain.CusID;
            addStepsPickMain.CustomerAddress = Pb_PiackMain.CustomerAddress;
            addStepsPickMain.Toexamine = Pb_PiackMain.Toexamine;
            addStepsPickMain.Memo = Pb_PiackMain.Memo;
            addStepsPickMain.ParentId = Pb_PiackMain.ParentId;
            addStepsPickMain.DeliveryTime = Pb_PiackMain.DeliveryTime;
            addStepsPickMain.BuildingId = Pb_PiackMain.BuildingId;
            addStepsPickMain.BuildingNum = Pb_PiackMain.BuildingNum;
            addStepsPickMain.Status = Pb_PiackMain.Status;
            List<StepsList> stepsLists = new List<StepsList>();
            var Steps = await Db.GetIQueryable<PB_PickListSteps>().Where(m => m.ParentId == ParentId && m.StepIndex != null).ToListAsync();
            List<string> liststr = new List<string>();
            var listd = Steps.GroupBy(x => new { x.StepIndex, }).Select(x => new { StepIndex = x.Key.StepIndex, Nums = x.Sum(n => n.StockVolume) });
            foreach (var item in listd)
            {
                liststr.Add(item.StepIndex);
                StepsList stepsList = new StepsList();
                stepsList.key = item.StepIndex;
                stepsList.childrenList = await GetParentid(ParentId, ItemId, item.StepIndex);
                stepsLists.Add(stepsList);
            }
            addStepsPickMain.SubData = stepsLists;
            return addStepsPickMain;


        }


        public async Task<List<childrenList>> GetParentid(string ParentId, string ItemId, string Key)
        {

            var _pickmain = await Db.GetIQueryable<PB_PickUpMain>().Where(m => m.Id == ParentId).FirstOrDefaultAsync();
            String sql = String.Empty;
            if (_pickmain.OrderType == 0)
            {
                sql = "SELECT a.ParentId BatchNumber,'{0}' AS StepIndex, a.AreaId,a.RackId,a.LocationId,a.MaterialId,a.SubId AS PB_DesignListInfo,a.Remarks AS Remarks,b.`Code` MaterialCode,b.`Name` MaterialName,IFNULL(b.Weight,0) Weight,b.Spec AS MaterialSpec,a.Id AS Id,c.`Name` LocationName,d.StorAreaName,d.`Name` StorageName,f.`Name` RackName,CASE  WHEN IFNULL(lm.ScanNum, 0 ) -IFNULL(lm.Nums_R, 0) < 0  THEN 0 ELSE  IFNULL(lm.ScanNum, 0) - IFNULL(lm.Nums_R, 0) END StockNumber,a.StockVolume AS StockVolume,a.StockVolume StockVolumecache,  a.ReadyNums,concat(a.MaterialId, '_', a.LocationId) AS `onlyId`,IFNULL(tb.RealNums, 0) AS StepNumber,CASE WHEN( IFNULL(tb.RealNums, 0) - IFNULL(tbp.ReadyNums, 0)) < 0 THEN  0 ELSE( IFNULL(tb.RealNums, 0) - IFNULL(tbp.ReadyNums, 0)) END AS ShouldNumber,grops.`Name` groupName  FROM PB_PickListSteps AS a LEFT JOIN PB_PickUpMain AS p ON a.ParentId = p.Id  LEFT JOIN PB_Material AS b ON a.MaterialId = b.Id LEFT JOIN Base_UnitItems as grops on b.storageId=grops.Id  LEFT JOIN PB_Location c ON a.LocationId = c.Id LEFT JOIN(SELECT m.Id, `Name`, m.StorAreaName FROM View_StorAreaRackLocation m LEFT JOIN Base_Department n ON m.StorId = n.id) d ON a.LocationId = d.id LEFT JOIN PB_Rack f ON c.RackId = f.id  LEFT JOIN IT_LocalMaterial AS lm ON a.LocationId = lm.LocalId  AND a.MaterialId = lm.MaterialId   LEFT JOIN(   SELECT  DesignId, MaterialId,  SUM(RealNums ) AS RealNums  FROM (   SELECT b.DesignId,    c.MaterialId,   IFNULL(c.{0},0) RealNums   FROM  PB_PickUpMain AS a    LEFT JOIN PB_DeliveryNoticeItem AS b ON a.ParentId = b.Id   LEFT JOIN PB_DesignDetail AS c ON b.DesignId = c.ParentId   WHERE   a.Id = '" + ParentId + "'  AND c.State != 2 UNION ALL   SELECT   b.DesignId,	c.MaterialId,-IFNULL(c.{0}, 0) AS RealNums   FROM   PB_PickUpMain AS a    LEFT JOIN PB_DeliveryNoticeItem AS b ON a.ParentId = b.Id   LEFT JOIN PB_DesignDetail AS c ON b.DesignId = c.ParentId  WHERE   a.Id = '" + ParentId + "'  AND c.State = 2) AS t    GROUP BY   DesignId,MaterialId	) AS tb ON a.MaterialId = tb.MaterialId LEFT JOIN( SELECT   a.ParentId,  b.MaterialId,   SUM(ReadyNums ) AS ReadyNums    FROM  PB_PickUpMain AS a  LEFT JOIN PB_PickListSteps AS b ON a.Id = b.ParentId WHERE  a.ParentId = '" + ItemId + "'  AND a.STATUS = 3  GROUP BY    a.ParentId,     b.MaterialId  ) AS tbp ON p.ParentId = tbp.ParentId  AND a.MaterialId = tbp.MaterialId  WHERE    a.ParentId = '" + ParentId + "'  AND a.StepIndex = '" + Key + "' ORDER BY a.Slot";
                sql = String.Format(sql, Key);
            }
            else
            {
                sql = "SELECT a.ParentId BatchNumber,'{0}' AS StepIndex, a.AreaId,a.RackId,a.LocationId,a.MaterialId,a.SubId AS PB_DesignListInfo,a.Remarks AS Remarks,b.`Code` MaterialCode,b.`Name` MaterialName,IFNULL(b.Weight,0) Weight,b.Spec AS MaterialSpec,a.Id AS Id,c.`Name` LocationName,d.StorAreaName,d.`Name` StorageName,f.`Name` RackName,CASE  WHEN IFNULL(lm.ScanNum, 0 ) -IFNULL(lm.Nums_R, 0) < 0  THEN 0 ELSE  IFNULL(lm.ScanNum, 0) - IFNULL(lm.Nums_R, 0) END StockNumber,a.StockVolume AS StockVolume,a.StockVolume StockVolumecache,  a.ReadyNums,concat(a.MaterialId, '_', a.LocationId) AS `onlyId`,IFNULL(tb.RealNums, 0) AS StepNumber,CASE WHEN( IFNULL(tb.RealNums, 0) - IFNULL(tbp.ReadyNums, 0)) < 0 THEN  0 ELSE( IFNULL(tb.RealNums, 0) - IFNULL(tbp.ReadyNums, 0)) END AS ShouldNumber,grops.`Name` groupName,	a.OriginalMaterialId OriginalMaterialId,  ormater.`Name` OriginalMaterialName,ormater.`Code` OriginalMaterialCode FROM PB_PickListSteps AS a LEFT JOIN PB_PickUpMain AS p ON a.ParentId = p.Id  LEFT JOIN PB_Material AS b ON a.MaterialId = b.Id LEFT JOIN PB_Material AS ormater ON a.OriginalMaterialId = ormater.Id  LEFT JOIN Base_UnitItems as grops on b.storageId=grops.Id  LEFT JOIN PB_Location c ON a.LocationId = c.Id LEFT JOIN(SELECT m.Id, `Name`, m.StorAreaName FROM View_StorAreaRackLocation m LEFT JOIN Base_Department n ON m.StorId = n.id) d ON a.LocationId = d.id LEFT JOIN PB_Rack f ON c.RackId = f.id  LEFT JOIN IT_LocalMaterial AS lm ON a.LocationId = lm.LocalId  AND a.MaterialId = lm.MaterialId   LEFT JOIN(   SELECT  DesignId, MaterialId,  SUM(RealNums ) AS RealNums  FROM (   SELECT b.DesignId,    c.MaterialId,   IFNULL(c.{0},0) RealNums   FROM  PB_PickUpMain AS a    LEFT JOIN PB_DeliveryNoticeItem AS b ON a.ParentId = b.Id   LEFT JOIN PB_DesignDetail AS c ON b.DesignId = c.ParentId   WHERE   a.Id = '" + ParentId + "'  AND c.State != 2 UNION ALL   SELECT   b.DesignId,	c.MaterialId,-IFNULL(c.{0}, 0) AS RealNums   FROM   PB_PickUpMain AS a    LEFT JOIN PB_DeliveryNoticeItem AS b ON a.ParentId = b.Id   LEFT JOIN PB_DesignDetail AS c ON b.DesignId = c.ParentId  WHERE   a.Id = '" + ParentId + "'  AND c.State = 2) AS t    GROUP BY   DesignId,MaterialId	) AS tb ON a.MaterialId = tb.MaterialId LEFT JOIN( SELECT   a.ParentId,  b.MaterialId,   SUM(ReadyNums ) AS ReadyNums    FROM  PB_PickUpMain AS a  LEFT JOIN PB_PickListSteps AS b ON a.Id = b.ParentId WHERE  a.ParentId = '" + ItemId + "'  AND a.STATUS = 3  GROUP BY    a.ParentId,     b.MaterialId  ) AS tbp ON p.ParentId = tbp.ParentId  AND a.MaterialId = tbp.MaterialId  WHERE    a.ParentId = '" + ParentId + "'  AND a.StepIndex = '" + Key + "' ORDER BY a.Slot";
                sql = String.Format(sql, Key);
            }

            var res = await Db.GetListBySqlAsync<childrenList>(sql.ToString());
            return res;
        }

        /// <summary>
        /// 编辑保存分批次备货
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<AjaxResult> UpdateStepsPickMain(AddStepsPickMain data)
        {
            //获取原有的备货单明细信息
            List<PB_PickListSteps> PickUpList = await Db.GetIQueryable<PB_PickListSteps>().Where(x => x.ParentId == data.Id).ToListAsync();
            string sqlMain = string.Empty;
            string StepNumber = string.Empty;

            foreach (var item in PickUpList)
            {
                //获取步数列
                StepNumber = item.StepIndex + "Ready";
                sqlMain += @" update  IT_LocalMaterial set Nums_R=IFNULL(Nums_R,0)-" + item.StockVolume + " WHERE LocalId='" + item.LocationId + "' AND MaterialId='" + item.MaterialId + "'; ";
                //减少设计清单步数已备量
                string stepsreduce = "update  PB_DesignDetail set " + StepNumber + "= IFNULL(" + StepNumber + ", 0)-" + item.StockVolume + " where MaterialId='" + item.MaterialId + "' AND Id='" + item.SubId + "'";
                await Db.ExecuteSqlAsync(stepsreduce);
            }
            //清空库存占用
            await ExecuteSqlAsync(sqlMain);
            await ExecuteSqlAsync(" delete from PB_PickListSteps where ParentId='" + data.Id + "'");
            await ExecuteSqlAsync(" delete from PB_PickUpList where ParentId='" + data.Id + "'");
            string steptitle = "";
            List<PB_PickUpList> pB_PickUpLists = new List<PB_PickUpList>();
            List<PB_PickListSteps> pB_PickListSteplist = new List<PB_PickListSteps>();
            #region 组装数据
            string Updatesql = "";
            for (int i = 0; i < data.SubData.Count; i++)
            {
                for (int k = 0; k < data.SubData[i].childrenList.Count; k++)
                {
                    PB_PickListSteps pB_PickListSteps = new PB_PickListSteps();
                    pB_PickListSteps.Id = IdHelper.GetId();//详情id
                    pB_PickListSteps.ParentId = data.Id;//主表ID
                    pB_PickListSteps.AreaId = data.SubData[i].childrenList[k].AreaId;//货区ID
                    pB_PickListSteps.RackId = data.SubData[i].childrenList[k].RackId;//货架ID
                    pB_PickListSteps.LocationId = data.SubData[i].childrenList[k].LocationId;//货位ID
                    pB_PickListSteps.StockVolume = data.SubData[i].childrenList[k].StockVolume;// 备货单明细数量
                    pB_PickListSteps.MaterialId = data.SubData[i].childrenList[k].MaterialId;//物料id
                    pB_PickListSteps.Remarks = data.SubData[i].childrenList[k].Remarks;//备注
                    pB_PickListSteps.CreateTime = DateTime.Now;//创建时间
                    pB_PickListSteps.CreatorId = _operator?.UserId; //创建人
                    pB_PickListSteps.SubId = data.SubData[i].childrenList[k].PB_DesignListInfo;
                    pB_PickListSteps.ReadyNums = 0;
                    pB_PickListSteps.State = 0;
                    pB_PickListSteps.Deleted = false;//伪删除
                    pB_PickListSteps.StepIndex = data.SubData[i].key;
                    pB_PickListSteps.Slot = k;
                    if (!string.IsNullOrEmpty(data.SubData?[i].childrenList[k].StockVolume.ToString()))
                    {
                        Updatesql += @"UPDATE IT_LocalMaterial SET Nums_R = IFNULL(Nums_R,0) +'" + data.SubData[i].childrenList[k].StockVolume + "' WHERE LocalId='" + data.SubData[i].childrenList[k].LocationId + "' AND MaterialId='" + data.SubData[i].childrenList[k].MaterialId + "'; ";
                    }
                    pB_PickListSteplist.Add(pB_PickListSteps);
                    //设计清单拼装已备货数量
                    steptitle = data.SubData[i].key + "Ready";
                    //反填设计清单已备数量
                    string sql = "update  PB_DesignDetail set " + steptitle + "= IFNULL(" + steptitle + ", 0)+" + data.SubData[i].childrenList[k].StockVolume + " where MaterialId='" + data.SubData[i].childrenList[k].MaterialId + "' AND Id='" + data.SubData[i].childrenList[k].PB_DesignListInfo + "'";
                    await Db.ExecuteSqlAsync(sql);
                }
            }
            #endregion


            if (pB_PickListSteplist.Count > 0)
            {
                await Db.InsertAsync<PB_PickListSteps>(pB_PickListSteplist);
                var PickListStepGroupList = pB_PickListSteplist.GroupBy(x => new { x.AreaId, x.RackId, x.LocationId, x.MaterialId, x.SubId }).Select(x => new { AreaId = x.Key.AreaId, RackId = x.Key.RackId, LocationId = x.Key.LocationId, MaterialId = x.Key.MaterialId, SubId = x.Key.SubId, StockVolume = x.Sum(n => n.StockVolume) });
                foreach (var item in PickListStepGroupList)
                {
                    //创建备货单
                    PB_PickUpList pB_PickUpList = new PB_PickUpList();
                    pB_PickUpList.Id = IdHelper.GetId();
                    pB_PickUpList.ParentId = data.Id;
                    pB_PickUpList.AreaId = item.AreaId;
                    pB_PickUpList.RackId = item.RackId;
                    pB_PickUpList.MaterialId = item.MaterialId;
                    pB_PickUpList.LocationId = item.LocationId;
                    pB_PickUpList.StockVolume = item.StockVolume;
                    pB_PickUpList.ReadyNums = 0;
                    pB_PickUpList.SubId = item.SubId;
                    pB_PickUpList.State = 0;
                    pB_PickUpList.CreateTime = DateTime.Now;
                    var pb_d = await Db.GetIQueryable<PB_DesignDetail>().Where(m => m.Id == pB_PickUpList.SubId).FirstOrDefaultAsync();
                    if (pb_d != null)
                    {
                        pB_PickUpList.Remarks = pb_d.Remarks;
                    }
                    else
                    {
                        pB_PickUpList.Remarks = "";
                    }
                    pB_PickUpList.CreatorId = _operator.UserId;
                    pB_PickUpList.Deleted = false;
                    pB_PickUpList.ShippedNums = 0;
                    pB_PickUpList.OddNumber = "";
                    pB_PickUpList.ShippingId = "";
                    pB_PickUpLists.Add(pB_PickUpList);

                }
                if (pB_PickUpLists.Count > 0)
                {
                    await Db.InsertAsync(pB_PickUpLists);
                }
            }
            if (Updatesql.Length > 0)
            {
                await ExecuteSqlAsync(Updatesql);
            }
            await ExecuteSqlAsync(" UPDATE  PB_PickUpMain set UpdateTime=NOW()  where Id='" + data.Id + "'");
            AjaxResult res = new AjaxResult
            {
                Success = true,
                Msg = "请求成功！"
            };

            return res;
        }

        //替换编辑保存分步备货

        public async Task<List<StepsSummary>> GetStepsSummaryList(string ParentId)
        {
            StringBuilder sql = new StringBuilder();

            sql.AppendLine("SELECT");
            sql.AppendLine("design.*, ");
            sql.AppendLine("IFNULL(steps.StockVolume, 0) StockVolume,    ");
            sql.AppendLine("IFNULL(steps.ReadyNums, 0) ReadyNums, ");
            sql.AppendLine("steps.StepIndex");
            sql.AppendLine("FROM");
            sql.AppendLine("(");
            sql.AppendLine("SELECT");
            sql.AppendLine("a.Id,");
            sql.AppendLine("d.`Name`,");
            sql.AppendLine("d.`Code`,");
            sql.AppendLine("a.RealNums,");
            sql.AppendLine("a.MaterialId,");
            sql.AppendLine("main.Id MainId");
            sql.AppendLine("FROM");
            sql.AppendLine("PB_DesignDetail AS a");
            sql.AppendLine("LEFT JOIN PB_DesignList AS b ON a.ParentId = b.Id    ");
            sql.AppendLine("LEFT JOIN PB_DeliveryNoticeItem AS c ON c.DesignId = b.Id    ");
            sql.AppendLine("LEFT JOIN PB_Material AS d ON a.MaterialId = d.Id    ");
            sql.AppendLine("LEFT JOIN PB_PickUpMain AS main ON c.Id = main.ParentId    ");
            sql.AppendLine("WHERE    ");
            sql.AppendLine("main.Id = '" + ParentId + "'");
            sql.AppendLine(") AS design    ");
            sql.AppendLine("LEFT JOIN(SELECT SubId, MaterialId, StepIndex, IFNULL(sum(StockVolume ), 0 ) AS StockVolume ,IFNULL(sum(ReadyNums ), 0) ReadyNums  FROM PB_PickListSteps  WHERE ParentId='" + ParentId + "' GROUP BY SubId, MaterialId, StepIndex ) AS steps ON  design.Id = steps.SubId    ");
            sql.AppendLine("AND design.MaterialId = steps.MaterialId    ");
            sql.AppendLine("WHERE");
            sql.AppendLine("steps.StockVolume > 0");
            var pb_detaillist = await Db.GetListBySqlAsync<StepsSummary>(sql.ToString());
            var detaillist = pb_detaillist.Select(s => s.Id).Distinct();
            List<StepsSummary> stepsSummaries = new List<StepsSummary>();
            foreach (var item in detaillist)
            {
                var tmpList = pb_detaillist.Where(s => s.Id == item).ToList();
                StepsSummary tmp = new StepsSummary();
                tmp.Name = tmpList[0].Name;
                tmp.Code = tmpList[0].Code;
                tmp.RealNums = tmpList[0].RealNums;
                tmp.MainId = tmpList[0].MainId;
                double _StockVolume = 0;
                string[] aa = { "OneStep", "TwoStep", "ThreeStep", "FourStep", "FiveStep", "SixStep", "SevenStep", "EightStep", "NineStep", "TenStep", "FifteenStep" };
                foreach (var items in aa)
                {
                    var entity = tmpList.FirstOrDefault(s => s.MainId == ParentId && s.StepIndex == items);
                    if (!entity.IsNullOrEmpty())
                    {

                        _StockVolume += Convert.ToDouble(entity.StockVolume);
                    }
                    switch (items)
                    {
                        case "OneStep":
                            tmp.OneStep = "0,0";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.OneStep = Convert.ToDouble(entity.StockVolume).ToString() + "," + Convert.ToDouble(entity.ReadyNums).ToString();
                            }
                            break;
                        case "TwoStep":
                            tmp.TwoStep = "0,0";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.TwoStep = Convert.ToDouble(entity.StockVolume).ToString() + "," + Convert.ToDouble(entity.ReadyNums).ToString();
                            }
                            break;
                        case "ThreeStep":
                            tmp.ThreeStep = "0,0";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.ThreeStep = Convert.ToDouble(entity.StockVolume).ToString() + "," + Convert.ToDouble(entity.ReadyNums).ToString();
                            }
                            break;
                        case "FourStep":
                            tmp.FourStep = "0,0";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.FourStep = Convert.ToDouble(entity.StockVolume).ToString() + "," + Convert.ToDouble(entity.ReadyNums).ToString();
                            }
                            break;
                        case "FiveStep":
                            tmp.FiveStep = "0,0";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.FiveStep = Convert.ToDouble(entity.StockVolume).ToString() + "," + Convert.ToDouble(entity.ReadyNums).ToString();
                            }
                            break;
                        case "SixStep":
                            tmp.SixStep = "0,0";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.SixStep = Convert.ToDouble(entity.StockVolume).ToString() + "," + Convert.ToDouble(entity.ReadyNums).ToString();
                            }
                            break;
                        case "SevenStep":
                            tmp.SevenStep = "0,0";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.SevenStep = Convert.ToDouble(entity.StockVolume).ToString() + "," + Convert.ToDouble(entity.ReadyNums).ToString();
                            }
                            break;
                        case "EightStep":
                            tmp.EightStep = "0,0";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.EightStep = Convert.ToDouble(entity.StockVolume).ToString() + "," + Convert.ToDouble(entity.ReadyNums).ToString();
                            }
                            break;
                        case "NineStep":
                            tmp.NineStep = "0,0";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.NineStep = Convert.ToDouble(entity.StockVolume).ToString() + "," + Convert.ToDouble(entity.ReadyNums).ToString();
                            }
                            break;
                        case "TenStep":
                            tmp.TenStep = "0,0";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.TenStep = Convert.ToDouble(entity.StockVolume).ToString() + "," + Convert.ToDouble(entity.ReadyNums).ToString();
                            }
                            break;
                        case "FifteenStep":
                            tmp.FifteenStep = "0,0";
                            if (!entity.IsNullOrEmpty())
                            {
                                tmp.FifteenStep = Convert.ToDouble(entity.StockVolume).ToString() + "," + Convert.ToDouble(entity.ReadyNums).ToString();
                            }
                            break;
                    }
                }

                tmp.StockVolume = _StockVolume.ToString();
                stepsSummaries.Add(tmp);
            }
            return stepsSummaries;
        }
        /// <summary>
        /// 通过发货通知单获取设计清单步级
        /// </summary>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        public async Task<int?> GetStepsIndex(string ParentId)
        {
            int? Value = 0;
            var pB_DeliveryNoticeItem = await Db.GetIQueryable<PB_DeliveryNoticeItem>().Where(m => m.Id == ParentId).FirstOrDefaultAsync();
            var pb_desl = await Db.GetIQueryable<PB_DesignList>().Where(m => m.Id == pB_DeliveryNoticeItem.DesignId).FirstOrDefaultAsync();
            if (pb_desl != null)
            {
                if (pb_desl.StepLevel.ToString().IsNullOrEmpty())
                {
                    Value = 7;
                }
                else
                {
                    Value = pb_desl.StepLevel;
                }

            }
            else
            {
                Value = 7;
            }
            return Value;
        }

        public async Task preparationSteps(PreparationStepsSearch data, MongoDBOptions _mongodbOptions)
        {
            List<PrintQueue> ori = new List<PrintQueue>();
            //判断步数是否大于0
            if (data.Step.Count > 0)
            {
                foreach (var item in data.Step)
                {
                    string sql = "SELECT IFNULL(SUM(StockVolume), 0)  StockVolume,'" + item + "' AS StepIndex,e.`Name`,f.Buildingnumber AS Bulider,	e.`Name` ProjectName, '河北盛卓建筑设备制造有限公司' as 'Company'FROM `PB_PickListSteps`  AS a LEFT JOIN PB_PickUpMain AS b on a.ParentId = b.Id LEFT JOIN PB_DeliveryNoticeItem AS c on b.ParentId = c.Id LEFT JOIN PB_DesignList AS d on c.DesignId = d.Id LEFT JOIN PB_Project AS e on d.ProjectId = e.Id LEFT JOIN PB_Buildingnumber AS f on d.BuildingNumberID = f.Id WHERE a.ParentId = '" + data.ParentId + "' AND a.StepIndex = '" + item + "'";
                    var PreparationStepsList = await Db.GetListBySqlAsync<PreparationSteps>(sql);

                    foreach (var items in PreparationStepsList)
                    {
                        string strguid = Guid.NewGuid().ToString("N");
                        PrintQueue printdata = new PrintQueue();
                        printdata.Id = IdHelper.GetId();
                        printdata.No = data.ParentId;
                        printdata.Name = items.ProjectName + items.Bulider;
                        printdata.Code = items.StepIndex == "OneStep" ? "第一步" : items.StepIndex == "TwoStep" ? "第二步" : items.StepIndex == "ThreeStep" ? "第三步" : items.StepIndex == "FourStep" ? "第四步" : items.StepIndex == "FiveStep" ? "第五步" : items.StepIndex == "SixStep" ? "第六步" : items.StepIndex == "SevenStep" ? "第七步" : items.StepIndex == "EightStep" ? "第八步" : items.StepIndex == "NineStep" ? "第九步" : items.StepIndex == "TenStep" ? "第九步" : "补加";
                        printdata.Type = "Steps";
                        printdata.QrCode = "0,0";
                        printdata.Dept = _operator.Property.DepartmentId;
                        printdata.Date = DateTime.Now.ToString("yyyy-MM-dd");
                        printdata.Printer = data.PrinterId;
                        printdata.TypeName = "NULL";
                        printdata.BatchNumber = strguid;
                        printdata.Status = (items.StockVolume).ToString();
                        printdata.JobCount = 1;
                        ori.Add(printdata);
                    }
                }
            }
            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
            //插入mongo队列
            await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, ori);
        }

        /// <summary>
        /// 修改备货单为完成状态
        /// </summary>
        /// <param name="PickMainId">备货单Id</param>
        /// <returns></returns>
        [Transactional]
        public async Task SubmitPickMainDataAsync(string PickMainId)
        {
            try
            {
                PB_PickUpMain pB_PickUpMain = await Db.GetIQueryable<PB_PickUpMain>().Where(x => x.Id == PickMainId).FirstOrDefaultAsync();
                List<PB_PickUpList> PickUpList = await Db.GetIQueryable<PB_PickUpList>().Where(x => x.ParentId == PickMainId).ToListAsync();
                int ToReviewStatus = 0;
                foreach (var item in PickUpList)
                {
                    if (item.ReadyNums != item.StockVolume)
                    {
                        ToReviewStatus = 1;
                    }
                }
                PickUpList = PickUpList.Where(x => x.ReadyNums < x.StockVolume).ToList();
                List<string> localIds = PickUpList.Select(x => x.LocationId).ToList();
                List<string> materialIds = PickUpList.Select(x => x.MaterialId).ToList();
                List<IT_LocalMaterial> iT_LocalMaterials = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => materialIds.Contains(x.MaterialId) && localIds.Contains(x.LocalId)).ToListAsync();
                foreach (var item in iT_LocalMaterials)
                {
                    var itemdata = PickUpList.Where(x => x.MaterialId == item.MaterialId && x.LocationId == item.LocalId).FirstOrDefault();
                    if (!itemdata.IsNullOrEmpty())
                    {
                        item.Nums_R -= Convert.ToDouble(itemdata.StockVolume - itemdata.ReadyNums);
                    }
                }

                pB_PickUpMain.Status = 3;
                pB_PickUpMain.ToReviewStatus = ToReviewStatus;
                await Db.UpdateAsync<PB_PickUpMain>(pB_PickUpMain);
                await Db.UpdateAsync<IT_LocalMaterial>(iT_LocalMaterials);
            }
            catch (Exception ex)
            {
                if (ex.Message.IsNullOrEmpty())
                {
                    throw new BusException("接口异常");
                }
                throw new BusException(ex.Message);
            }
        }

        #endregion

        #region 私有成员

        #endregion
    }
}